Elffuss BraidHub

utopia-ia/elffuss-braid public

Format v1: codec, names, trees, changesets; frozen and cross-checked

Implements and freezes the hashed format described in
docs/spec/format-v1.md:
- codec: shortest-form LEB128, zigzag, length-prefixed bytes; the
  decoder rejects overlong integers, overflow, lengths past the end and
  trailing bytes.
- names: rejects empty, '/', NUL, '.', '..', and every alias of .braid
  or .git (case, NFC, HFS+ ignorable code points, NTFS trailing dots,
  spaces and streams, 8.3 short names); some names may not be symlinks.
- trees: flat up to 1,024 entries, split by name hash above that, so
  equal entry sets give equal ids; read_directory rebuilds to verify.
- changesets: per-file changes against the first parent, inline up to
  64 KiB or in a separate blob, raw extras and git origin.

Golden vectors are recomputed by docs/spec/check_vectors.py, a second
implementation written from the specification and hashed with b3sum.
Property tests cover canonical round trips, order independence and
edit locality; three cargo-fuzz targets check that anything that
decodes re-encodes to the same bytes. CI gains both checks.
Changeset9a8c85a8ae0e5e1f3ecf0decd3aab79560140a90d7b9e75e3285f2e65434ba94
AuthorKikoCis <KikoCis@users.noreply.github.com> · 2026-10-15 20:43 +02:00
CommitterKikoCis <KikoCis@users.noreply.github.com> · 2026-10-15 20:43 +02:00
Parents0cba57aa99aa

Browse the files at this changeset

19 files changed

modified .github/workflows/ci.yml +26 −0
@@ -64,3 +64,29 @@
6464 with:
6565 fetch-depth: 0
6666 - run: scripts/privacy-check.sh
67+
68+ spec:
69+ name: spec vectors (independent implementation)
70+ runs-on: ubuntu-latest
71+ steps:
72+ - uses: actions/checkout@v5
73+ - uses: dtolnay/rust-toolchain@stable
74+ - uses: Swatinem/rust-cache@v2
75+ - run: cargo install b3sum --locked
76+ - run: python3 docs/spec/check_vectors.py
77+
78+ fuzz:
79+ name: fuzz smoke test
80+ runs-on: ubuntu-latest
81+ steps:
82+ - uses: actions/checkout@v5
83+ - uses: dtolnay/rust-toolchain@nightly
84+ - uses: taiki-e/install-action@v2
85+ with:
86+ tool: cargo-fuzz
87+ - name: run every target for one minute
88+ working-directory: fuzz
89+ run: |
90+ for target in decode_tree decode_changeset names; do
91+ cargo fuzz run "$target" -- -max_total_time=60
92+ done
modified CONTRIBUTING.md +3 −2
@@ -31,8 +31,9 @@
3131 list of accepted licences.
3232 - **Hashed formats are specified first.** A change to the bytes of an id, a
3333 tree or a changeset needs an update to `docs/spec/format-v1.md` and to its
34- golden vectors in the same pull request. After milestone 1 such a change
35- needs a new format version.
34+ golden vectors in the same pull request, and `docs/spec/check_vectors.py`
35+ must still pass. Format v1 is frozen, so such a change needs a new format
36+ version.
3637 - **Performance claims come with a reproducible script** and are stated as a
3738 ratio against git on the same machine. Do not publish absolute timings or
3839 describe your hardware.
modified Cargo.lock +266 −0
@@ -64,6 +64,31 @@
6464 source = "registry+https://github.com/rust-lang/crates.io-index"
6565 checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56"
6666
67+[[package]]
68+name = "autocfg"
69+version = "1.5.1"
70+source = "registry+https://github.com/rust-lang/crates.io-index"
71+checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
72+
73+[[package]]
74+name = "bit-set"
75+version = "0.11.1"
76+source = "registry+https://github.com/rust-lang/crates.io-index"
77+checksum = "56d87354e4229f54a44f7bf2435906a4656dba36026ab6eaca629a2c436a691c"
78+dependencies = [
79+ "bit-vec",
80+]
81+
82+[[package]]
83+name = "bit-vec"
84+version = "0.10.1"
85+source = "registry+https://github.com/rust-lang/crates.io-index"
86+checksum = "5727b15fa97d4f4fee0a3b7c3d550ed0269f54329207b86388de918604e31269"
87+dependencies = [
88+ "borsh",
89+ "serde",
90+]
91+
6792 [[package]]
6893 name = "bitflags"
6994 version = "2.13.2"
@@ -83,6 +108,36 @@
83108 "cpufeatures",
84109 ]
85110
111+[[package]]
112+name = "borsh"
113+version = "1.8.1"
114+source = "registry+https://github.com/rust-lang/crates.io-index"
115+checksum = "553c5d846a6ba5150c65e3b1b8ec073bcf1abc20f9b7220de384a4443ea4e20a"
116+dependencies = [
117+ "borsh-derive",
118+ "bytes",
119+ "cfg_aliases",
120+]
121+
122+[[package]]
123+name = "borsh-derive"
124+version = "1.8.1"
125+source = "registry+https://github.com/rust-lang/crates.io-index"
126+checksum = "12cdfe656708a01f89b451a7d36466e6fe6c414de0aa18fc54f864f6f9ca9f56"
127+dependencies = [
128+ "once_cell",
129+ "proc-macro-crate",
130+ "proc-macro2",
131+ "quote",
132+ "syn",
133+]
134+
135+[[package]]
136+name = "bytes"
137+version = "1.12.1"
138+source = "registry+https://github.com/rust-lang/crates.io-index"
139+checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"
140+
86141 [[package]]
87142 name = "cc"
88143 version = "1.8.0"
@@ -99,6 +154,23 @@
99154 source = "registry+https://github.com/rust-lang/crates.io-index"
100155 checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
101156
157+[[package]]
158+name = "cfg_aliases"
159+version = "0.2.2"
160+source = "registry+https://github.com/rust-lang/crates.io-index"
161+checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"
162+
163+[[package]]
164+name = "chacha20"
165+version = "0.10.2"
166+source = "registry+https://github.com/rust-lang/crates.io-index"
167+checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06"
168+dependencies = [
169+ "cfg-if",
170+ "cpufeatures",
171+ "rand_core",
172+]
173+
102174 [[package]]
103175 name = "clap"
104176 version = "4.6.7"
@@ -151,6 +223,12 @@
151223 source = "registry+https://github.com/rust-lang/crates.io-index"
152224 checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b"
153225
226+[[package]]
227+name = "core_detect"
228+version = "1.0.0"
229+source = "registry+https://github.com/rust-lang/crates.io-index"
230+checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48"
231+
154232 [[package]]
155233 name = "cpufeatures"
156234 version = "0.3.1"
@@ -176,8 +254,16 @@
176254 version = "0.0.1"
177255 dependencies = [
178256 "blake3",
257+ "proptest",
258+ "unicode-normalization",
179259 ]
180260
261+[[package]]
262+name = "equivalent"
263+version = "1.0.3"
264+source = "registry+https://github.com/rust-lang/crates.io-index"
265+checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826"
266+
181267 [[package]]
182268 name = "errno"
183269 version = "0.3.14"
@@ -200,6 +286,12 @@
200286 source = "registry+https://github.com/rust-lang/crates.io-index"
201287 checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484"
202288
289+[[package]]
290+name = "fnv"
291+version = "1.0.7"
292+source = "registry+https://github.com/rust-lang/crates.io-index"
293+checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
294+
203295 [[package]]
204296 name = "getrandom"
205297 version = "0.4.3"
@@ -209,14 +301,31 @@
209301 "cfg-if",
210302 "libc",
211303 "r-efi",
304+ "rand_core",
212305 ]
213306
307+[[package]]
308+name = "hashbrown"
309+version = "0.17.1"
310+source = "registry+https://github.com/rust-lang/crates.io-index"
311+checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
312+
214313 [[package]]
215314 name = "heck"
216315 version = "0.5.0"
217316 source = "registry+https://github.com/rust-lang/crates.io-index"
218317 checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
219318
319+[[package]]
320+name = "indexmap"
321+version = "2.14.2"
322+source = "registry+https://github.com/rust-lang/crates.io-index"
323+checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
324+dependencies = [
325+ "equivalent",
326+ "hashbrown",
327+]
328+
220329 [[package]]
221330 name = "is_terminal_polyfill"
222331 version = "1.70.2"
@@ -247,6 +356,15 @@
247356 source = "registry+https://github.com/rust-lang/crates.io-index"
248357 checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
249358
359+[[package]]
360+name = "num-traits"
361+version = "0.2.19"
362+source = "registry+https://github.com/rust-lang/crates.io-index"
363+checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
364+dependencies = [
365+ "autocfg",
366+]
367+
250368 [[package]]
251369 name = "once_cell"
252370 version = "1.21.4"
@@ -259,6 +377,15 @@
259377 source = "registry+https://github.com/rust-lang/crates.io-index"
260378 checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
261379
380+[[package]]
381+name = "proc-macro-crate"
382+version = "3.5.0"
383+source = "registry+https://github.com/rust-lang/crates.io-index"
384+checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f"
385+dependencies = [
386+ "toml_edit",
387+]
388+
262389 [[package]]
263390 name = "proc-macro2"
264391 version = "1.0.107"
@@ -268,6 +395,32 @@
268395 "unicode-ident",
269396 ]
270397
398+[[package]]
399+name = "proptest"
400+version = "1.12.0"
401+source = "registry+https://github.com/rust-lang/crates.io-index"
402+checksum = "b8530004ccb15eae51c7e40009fbe317f341f804db54dc033eec1c50be28cfa0"
403+dependencies = [
404+ "bit-set",
405+ "bit-vec",
406+ "bitflags",
407+ "chacha20",
408+ "core_detect",
409+ "num-traits",
410+ "rand",
411+ "rand_xorshift",
412+ "regex-syntax",
413+ "rusty-fork",
414+ "tempfile",
415+ "unarray",
416+]
417+
418+[[package]]
419+name = "quick-error"
420+version = "1.2.3"
421+source = "registry+https://github.com/rust-lang/crates.io-index"
422+checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0"
423+
271424 [[package]]
272425 name = "quote"
273426 version = "1.0.47"
@@ -283,6 +436,37 @@
283436 source = "registry+https://github.com/rust-lang/crates.io-index"
284437 checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
285438
439+[[package]]
440+name = "rand"
441+version = "0.10.3"
442+source = "registry+https://github.com/rust-lang/crates.io-index"
443+checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af"
444+dependencies = [
445+ "getrandom",
446+ "rand_core",
447+]
448+
449+[[package]]
450+name = "rand_core"
451+version = "0.10.1"
452+source = "registry+https://github.com/rust-lang/crates.io-index"
453+checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"
454+
455+[[package]]
456+name = "rand_xorshift"
457+version = "0.5.0"
458+source = "registry+https://github.com/rust-lang/crates.io-index"
459+checksum = "60aa6af80be32871323012e02e6e65f8a7cc7890931ae421d217ad8fe0df2ccf"
460+dependencies = [
461+ "rand_core",
462+]
463+
464+[[package]]
465+name = "regex-syntax"
466+version = "0.8.11"
467+source = "registry+https://github.com/rust-lang/crates.io-index"
468+checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
469+
286470 [[package]]
287471 name = "rustix"
288472 version = "1.1.5"
@@ -296,6 +480,18 @@
296480 "windows-sys",
297481 ]
298482
483+[[package]]
484+name = "rusty-fork"
485+version = "0.3.1"
486+source = "registry+https://github.com/rust-lang/crates.io-index"
487+checksum = "cc6bf79ff24e648f6da1f8d1f011e9cac26491b619e6b9280f2b47f1774e6ee2"
488+dependencies = [
489+ "fnv",
490+ "quick-error",
491+ "tempfile",
492+ "wait-timeout",
493+]
494+
299495 [[package]]
300496 name = "serde"
301497 version = "1.0.229"
@@ -303,6 +499,7 @@
303499 checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
304500 dependencies = [
305501 "serde_core",
502+ "serde_derive",
306503 ]
307504
308505 [[package]]
@@ -374,18 +571,78 @@
374571 "windows-sys",
375572 ]
376573
574+[[package]]
575+name = "tinyvec"
576+version = "1.13.3"
577+source = "registry+https://github.com/rust-lang/crates.io-index"
578+checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee"
579+
580+[[package]]
581+name = "toml_datetime"
582+version = "1.1.2+spec-1.1.0"
583+source = "registry+https://github.com/rust-lang/crates.io-index"
584+checksum = "2b86d767906c6c42421dcba507eb9d203e779497710a47782a224bb871653053"
585+dependencies = [
586+ "serde_core",
587+]
588+
589+[[package]]
590+name = "toml_edit"
591+version = "0.25.17+spec-1.1.0"
592+source = "registry+https://github.com/rust-lang/crates.io-index"
593+checksum = "e3641d5bbb5349a79e1020a242d251efbc546ad8048d133958323ce9c40a9c9c"
594+dependencies = [
595+ "indexmap",
596+ "toml_datetime",
597+ "toml_parser",
598+ "winnow",
599+]
600+
601+[[package]]
602+name = "toml_parser"
603+version = "1.1.5+spec-1.1.0"
604+source = "registry+https://github.com/rust-lang/crates.io-index"
605+checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c"
606+dependencies = [
607+ "winnow",
608+]
609+
610+[[package]]
611+name = "unarray"
612+version = "0.1.4"
613+source = "registry+https://github.com/rust-lang/crates.io-index"
614+checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94"
615+
377616 [[package]]
378617 name = "unicode-ident"
379618 version = "1.0.27"
380619 source = "registry+https://github.com/rust-lang/crates.io-index"
381620 checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
382621
622+[[package]]
623+name = "unicode-normalization"
624+version = "0.1.25"
625+source = "registry+https://github.com/rust-lang/crates.io-index"
626+checksum = "5fd4f6878c9cb28d874b009da9e8d183b5abc80117c40bbd187a1fde336be6e8"
627+dependencies = [
628+ "tinyvec",
629+]
630+
383631 [[package]]
384632 name = "utf8parse"
385633 version = "0.2.2"
386634 source = "registry+https://github.com/rust-lang/crates.io-index"
387635 checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
388636
637+[[package]]
638+name = "wait-timeout"
639+version = "0.2.1"
640+source = "registry+https://github.com/rust-lang/crates.io-index"
641+checksum = "09ac3b126d3914f9849036f826e054cbabdc8519970b8998ddaf3b5bd3c65f11"
642+dependencies = [
643+ "libc",
644+]
645+
389646 [[package]]
390647 name = "windows-link"
391648 version = "0.2.1"
@@ -401,6 +658,15 @@
401658 "windows-link",
402659 ]
403660
661+[[package]]
662+name = "winnow"
663+version = "1.0.4"
664+source = "registry+https://github.com/rust-lang/crates.io-index"
665+checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81"
666+dependencies = [
667+ "memchr",
668+]
669+
404670 [[package]]
405671 name = "zmij"
406672 version = "1.0.23"
modified Cargo.toml +3 −0
@@ -1,6 +1,7 @@
11 [workspace]
22 resolver = "3"
33 members = ["crates/*"]
4+exclude = ["fuzz"]
45
56 [workspace.package]
67 version = "0.0.1"
@@ -18,6 +19,8 @@
1819 clap = { version = "4.6", features = ["derive"] }
1920 serde_json = "1.0"
2021 tempfile = "3"
22+unicode-normalization = "0.1"
23+proptest = "1.12"
2124
2225 [workspace.lints.rust]
2326 unsafe_code = "deny"
modified README.md +12 −7
@@ -91,7 +91,8 @@
9191
9292 ## Quick start
9393
94-Today braid computes object ids. Everything else arrives milestone by milestone.
94+Today braid computes object ids, and its hashed format is frozen and verified.
95+Storing data arrives with milestone 2.
9596
9697 ```bash
9798 git clone https://github.com/KikoCis/elffuss-braid
@@ -134,8 +135,8 @@
134135 | Milestone | Scope | State |
135136 |---|---|---|
136137 | 0 | Public repository, CI, object ids, `braid hash-object` | ✅ done |
137-| 1 | Format v1: canonical codec, trees (flat and split), changesets, name rules; then frozen | in progress |
138-| 2 | Local store and op log: many processes, crash-safe, `fsck`, `undo` | planned |
138+| 1 | Format v1: canonical codec, trees (flat and split), changesets, name rules; frozen | ✅ done |
139+| 2 | Local store and op log: many processes, crash-safe, `fsck`, `undo` | next |
139140 | 3 | History and the git bridge: import, export, `log`, `show`, `diff`, `blame` | planned |
140141 | 4 | Many agents on one machine: workspaces, `land`, conflicts, `git sync` | planned |
141142 | 5 | Performance: deltas, chunking, derived indexes, benchmarks against git | planned |
@@ -149,12 +150,15 @@
149150
150151 ## What is honest about this
151152
152-- **It is pre-alpha.** Today it computes object ids and nothing else. Do not
153- keep anything in it that you cannot afford to lose.
153+- **It is pre-alpha.** Today it computes object ids and encodes the frozen
154+ format; it does not store anything yet. Do not keep anything in it that you
155+ cannot afford to lose.
154156 - **No performance claims yet.** When benchmarks land they will be ratios
155157 against git on the same machine, with the script that reproduces them, never
156158 numbers nobody can check.
157-- **The format can still change** until milestone 1 freezes it.
159+- **The hashed format is frozen** and every golden vector is recomputed by a
160+ second implementation written from the specification alone. Storage and
161+ protocols can still change.
158162 - **Braid is not Scion.** It starts from the ideas Anthropic described in
159163 public about its own source control system. It is an independent
160164 implementation, contains no code from Anthropic, and is not affiliated with
@@ -209,5 +213,6 @@
209213 Es una implementación independiente, sin código de Anthropic y sin relación con
210214 la empresa.
211215
212-Hoy está en pre-alfa: solo calcula ids de objetos. Las [fases](#status-and-roadmap)
216+Hoy está en pre-alfa: calcula ids y tiene el formato v1 congelado y verificado,
217+pero todavía no guarda datos. Las [fases](#status-and-roadmap)
213218 dicen qué llega después y qué pruebas tiene que pasar cada una.
modified crates/format/Cargo.toml +4 −0
@@ -14,6 +14,10 @@
1414
1515 [dependencies]
1616 blake3.workspace = true
17+unicode-normalization.workspace = true
18+
19+[dev-dependencies]
20+proptest.workspace = true
1721
1822 [lints]
1923 workspace = true
added crates/format/src/changeset.rs +675 −0
@@ -0,0 +1,675 @@
1+// SPDX-License-Identifier: Apache-2.0
2+// Copyright (c) 2026 UtopiaIA
3+
4+//! Changesets: one change to the repository.
5+//!
6+//! A changeset names its parents, the root tree it produces, and the files
7+//! that changed relative to its **first** parent. The change list makes
8+//! history, blame and rebase cheap; the root tree id makes the changeset
9+//! commit to the whole repository state. A store only accepts a changeset
10+//! whose change list, applied to the first parent's tree, gives exactly that
11+//! root (see the admission check in the store).
12+
13+use core::fmt;
14+
15+use crate::codec::{DecodeError, Reader, put_bytes, put_id, put_sv, put_uv};
16+use crate::id::{Kind, ObjectId};
17+use crate::name::{PathError, forbidden_as_symlink, validate_path};
18+use crate::tree::{EntryKind, GitId};
19+
20+/// Format byte of every changeset.
21+pub const FORMAT: u8 = 1;
22+
23+/// A change list whose encoding is at most this many bytes is stored inside
24+/// the changeset; a longer one is stored as a separate blob.
25+pub const MAX_INLINE_CHANGES_BYTES: usize = 64 * 1024;
26+
27+/// What happened to one path.
28+#[derive(Clone, Debug, PartialEq, Eq, Hash)]
29+pub enum ChangeOp {
30+ /// The path no longer exists.
31+ Delete,
32+ /// The path is now this regular file.
33+ File { blob: ObjectId, size: u64 },
34+ /// The path is now this executable file.
35+ Executable { blob: ObjectId, size: u64 },
36+ /// The path is now this symlink.
37+ Symlink { blob: ObjectId, size: u64 },
38+ /// The path is now this git submodule.
39+ Gitlink { commit: GitId },
40+}
41+
42+impl ChangeOp {
43+ /// The operation that sets a path to a tree entry of this kind. Trees are
44+ /// not files, so they have none: changes are always per file.
45+ pub fn from_entry(kind: &EntryKind) -> Option<Self> {
46+ Some(match kind {
47+ EntryKind::File { blob, size } => ChangeOp::File {
48+ blob: *blob,
49+ size: *size,
50+ },
51+ EntryKind::Executable { blob, size } => ChangeOp::Executable {
52+ blob: *blob,
53+ size: *size,
54+ },
55+ EntryKind::Symlink { blob, size } => ChangeOp::Symlink {
56+ blob: *blob,
57+ size: *size,
58+ },
59+ EntryKind::Gitlink { commit } => ChangeOp::Gitlink { commit: *commit },
60+ EntryKind::Tree { .. } => return None,
61+ })
62+ }
63+
64+ /// The tree entry this operation sets, or `None` for a delete.
65+ pub fn to_entry(&self) -> Option<EntryKind> {
66+ Some(match self {
67+ ChangeOp::Delete => return None,
68+ ChangeOp::File { blob, size } => EntryKind::File {
69+ blob: *blob,
70+ size: *size,
71+ },
72+ ChangeOp::Executable { blob, size } => EntryKind::Executable {
73+ blob: *blob,
74+ size: *size,
75+ },
76+ ChangeOp::Symlink { blob, size } => EntryKind::Symlink {
77+ blob: *blob,
78+ size: *size,
79+ },
80+ ChangeOp::Gitlink { commit } => EntryKind::Gitlink { commit: *commit },
81+ })
82+ }
83+}
84+
85+/// One changed path.
86+#[derive(Clone, Debug, PartialEq, Eq, Hash)]
87+pub struct Change {
88+ /// The full path, names joined by `/`.
89+ pub path: Vec<u8>,
90+ /// What happened to it.
91+ pub op: ChangeOp,
92+}
93+
94+impl Change {
95+ fn encode(&self, out: &mut Vec<u8>) {
96+ put_bytes(out, &self.path);
97+ match &self.op {
98+ ChangeOp::Delete => out.push(0),
99+ ChangeOp::File { blob, size } => {
100+ out.push(1);
101+ put_id(out, blob);
102+ put_uv(out, *size);
103+ }
104+ ChangeOp::Executable { blob, size } => {
105+ out.push(2);
106+ put_id(out, blob);
107+ put_uv(out, *size);
108+ }
109+ ChangeOp::Symlink { blob, size } => {
110+ out.push(3);
111+ put_id(out, blob);
112+ put_uv(out, *size);
113+ }
114+ ChangeOp::Gitlink { commit } => {
115+ out.push(4);
116+ commit.encode(out);
117+ }
118+ }
119+ }
120+
121+ /// Checks the path, and that a symlink does not take a name git or braid reads.
122+ fn validate(&self) -> Result<(), ChangesetError> {
123+ validate_path(&self.path).map_err(|error| ChangesetError::Path {
124+ path: self.path.clone(),
125+ error,
126+ })?;
127+ let last = self.path.rsplit(|byte| *byte == b'/').next().unwrap_or(&[]);
128+ if matches!(self.op, ChangeOp::Symlink { .. }) && forbidden_as_symlink(last) {
129+ return Err(ChangesetError::SymlinkName(self.path.clone()));
130+ }
131+ Ok(())
132+ }
133+
134+ fn decode(reader: &mut Reader<'_>) -> Result<Self, ChangesetError> {
135+ let path = reader.bytes()?.to_vec();
136+ let at = reader.position();
137+ let op = match reader.u8()? {
138+ 0 => ChangeOp::Delete,
139+ 1 => ChangeOp::File {
140+ blob: reader.id()?,
141+ size: reader.uv()?,
142+ },
143+ 2 => ChangeOp::Executable {
144+ blob: reader.id()?,
145+ size: reader.uv()?,
146+ },
147+ 3 => ChangeOp::Symlink {
148+ blob: reader.id()?,
149+ size: reader.uv()?,
150+ },
151+ 4 => ChangeOp::Gitlink {
152+ commit: GitId::decode(reader)?,
153+ },
154+ _ => {
155+ return Err(DecodeError::Invalid {
156+ at,
157+ what: "change operation",
158+ }
159+ .into());
160+ }
161+ };
162+ let change = Change { path, op };
163+ change.validate()?;
164+ Ok(change)
165+ }
166+}
167+
168+/// Smallest possible encoded change: a 1-byte path and a delete.
169+const MIN_CHANGE_BYTES: usize = 1 + 1 + 1;
170+
171+/// Who made or committed a change, and when.
172+#[derive(Clone, Debug, PartialEq, Eq, Hash)]
173+pub struct Signature {
174+ /// Name, as raw bytes.
175+ pub name: Vec<u8>,
176+ /// E-mail address, as raw bytes.
177+ pub email: Vec<u8>,
178+ /// Seconds since the Unix epoch.
179+ pub seconds: i64,
180+ /// Offset from UTC in minutes.
181+ pub offset_minutes: i64,
182+}
183+
184+impl Signature {
185+ fn encode(&self, out: &mut Vec<u8>) {
186+ put_bytes(out, &self.name);
187+ put_bytes(out, &self.email);
188+ put_sv(out, self.seconds);
189+ put_sv(out, self.offset_minutes);
190+ }
191+
192+ fn decode(reader: &mut Reader<'_>) -> Result<Self, DecodeError> {
193+ Ok(Signature {
194+ name: reader.bytes()?.to_vec(),
195+ email: reader.bytes()?.to_vec(),
196+ seconds: reader.sv()?,
197+ offset_minutes: reader.sv()?,
198+ })
199+ }
200+}
201+
202+/// Where the change list is.
203+#[derive(Clone, Debug, PartialEq, Eq)]
204+pub enum Changes {
205+ /// Inside the changeset.
206+ Inline(Vec<Change>),
207+ /// In a separate blob holding the encoded list.
208+ External {
209+ /// Id of the blob with the encoded list.
210+ list: ObjectId,
211+ /// Number of changes in it.
212+ count: u64,
213+ },
214+}
215+
216+/// A decoded changeset.
217+#[derive(Clone, Debug, PartialEq, Eq)]
218+pub struct Changeset {
219+ /// Parent changesets; the first is the base of the change list.
220+ pub parents: Vec<ObjectId>,
221+ /// Root tree of the repository after this change.
222+ pub root: ObjectId,
223+ /// The files that changed relative to the first parent.
224+ pub changes: Changes,
225+ /// Who wrote the change.
226+ pub author: Signature,
227+ /// Who recorded it.
228+ pub committer: Signature,
229+ /// The message, as raw bytes.
230+ pub message: Vec<u8>,
231+ /// Extra fields, in order, duplicates allowed.
232+ pub extras: Vec<(Vec<u8>, Vec<u8>)>,
233+ /// For a changeset imported from git: the blob with the original commit.
234+ pub git_origin: Option<ObjectId>,
235+}
236+
237+/// Why a changeset or change list is not valid.
238+#[derive(Clone, Debug, PartialEq, Eq)]
239+pub enum ChangesetError {
240+ /// The bytes are not a canonical encoding.
241+ Decode(DecodeError),
242+ /// A path is not valid.
243+ Path { path: Vec<u8>, error: PathError },
244+ /// Paths are not strictly ascending; `index` is the first out of order.
245+ Unsorted { index: usize },
246+ /// A symlink takes a name that git or braid reads.
247+ SymlinkName(Vec<u8>),
248+ /// An inline change list is longer than [`MAX_INLINE_CHANGES_BYTES`].
249+ InlineTooLong(usize),
250+}
251+
252+impl fmt::Display for ChangesetError {
253+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
254+ match self {
255+ ChangesetError::Decode(err) => write!(f, "{err}"),
256+ ChangesetError::Path { path, error } => {
257+ write!(f, "path {:?}: {error}", String::from_utf8_lossy(path))
258+ }
259+ ChangesetError::Unsorted { index } => {
260+ write!(f, "change {index} is out of order or a duplicate")
261+ }
262+ ChangesetError::SymlinkName(path) => write!(
263+ f,
264+ "symlink {:?} takes a name that must not be a symlink",
265+ String::from_utf8_lossy(path)
266+ ),
267+ ChangesetError::InlineTooLong(len) => write!(
268+ f,
269+ "inline change list of {len} bytes is longer than {MAX_INLINE_CHANGES_BYTES}"
270+ ),
271+ }
272+ }
273+}
274+
275+impl std::error::Error for ChangesetError {}
276+
277+impl From<DecodeError> for ChangesetError {
278+ fn from(err: DecodeError) -> Self {
279+ ChangesetError::Decode(err)
280+ }
281+}
282+
283+fn check_ascending(changes: &[Change]) -> Result<(), ChangesetError> {
284+ for (index, pair) in changes.windows(2).enumerate() {
285+ if pair[0].path >= pair[1].path {
286+ return Err(ChangesetError::Unsorted { index: index + 1 });
287+ }
288+ }
289+ Ok(())
290+}
291+
292+/// Encodes a change list: the count, then each change. This is both the
293+/// inline form and the content of an external change-list blob.
294+pub fn encode_change_list(changes: &[Change]) -> Vec<u8> {
295+ let mut out = Vec::new();
296+ put_uv(&mut out, changes.len() as u64);
297+ for change in changes {
298+ change.encode(&mut out);
299+ }
300+ out
301+}
302+
303+fn read_change_list(reader: &mut Reader<'_>) -> Result<Vec<Change>, ChangesetError> {
304+ let count = reader.count(MIN_CHANGE_BYTES)?;
305+ let mut changes = Vec::with_capacity(count);
306+ for _ in 0..count {
307+ changes.push(Change::decode(reader)?);
308+ }
309+ check_ascending(&changes)?;
310+ Ok(changes)
311+}
312+
313+/// Decodes the content of an external change-list blob.
314+pub fn decode_change_list(bytes: &[u8]) -> Result<Vec<Change>, ChangesetError> {
315+ let mut reader = Reader::new(bytes);
316+ let changes = read_change_list(&mut reader)?;
317+ reader.finish()?;
318+ Ok(changes)
319+}
320+
321+/// Everything a changeset is made of, before the change list is placed.
322+#[derive(Clone, Debug, PartialEq, Eq)]
323+pub struct ChangesetParts {
324+ /// Parent changesets; the first is the base of the change list.
325+ pub parents: Vec<ObjectId>,
326+ /// Root tree after the change.
327+ pub root: ObjectId,
328+ /// The changed paths, in any order.
329+ pub changes: Vec<Change>,
330+ /// Who wrote the change.
331+ pub author: Signature,
332+ /// Who recorded it.
333+ pub committer: Signature,
334+ /// The message.
335+ pub message: Vec<u8>,
336+ /// Extra fields.
337+ pub extras: Vec<(Vec<u8>, Vec<u8>)>,
338+ /// For an import from git: the blob with the original commit.
339+ pub git_origin: Option<ObjectId>,
340+}
341+
342+/// A changeset in canonical form, ready to store.
343+#[derive(Clone, Debug, PartialEq, Eq)]
344+pub struct Assembled {
345+ /// The changeset.
346+ pub changeset: Changeset,
347+ /// Its id.
348+ pub id: ObjectId,
349+ /// Its encoding.
350+ pub encoded: Vec<u8>,
351+ /// The change-list blob to store alongside it, when the list is external.
352+ pub external_list: Option<(ObjectId, Vec<u8>)>,
353+}
354+
355+impl ChangesetParts {
356+ /// Sorts and checks the change list, places it inline or in its own blob,
357+ /// and encodes the result.
358+ pub fn assemble(mut self) -> Result<Assembled, ChangesetError> {
359+ self.changes.sort_by(|a, b| a.path.cmp(&b.path));
360+ check_ascending(&self.changes)?;
361+ for change in &self.changes {
362+ change.validate()?;
363+ }
364+ let list = encode_change_list(&self.changes);
365+ let (changes, external_list) = if list.len() <= MAX_INLINE_CHANGES_BYTES {
366+ (Changes::Inline(self.changes), None)
367+ } else {
368+ let id = ObjectId::hash(Kind::Blob, &list);
369+ (
370+ Changes::External {
371+ list: id,
372+ count: self.changes.len() as u64,
373+ },
374+ Some((id, list)),
375+ )
376+ };
377+ let changeset = Changeset {
378+ parents: self.parents,
379+ root: self.root,
380+ changes,
381+ author: self.author,
382+ committer: self.committer,
383+ message: self.message,
384+ extras: self.extras,
385+ git_origin: self.git_origin,
386+ };
387+ let encoded = changeset.encode();
388+ let id = ObjectId::hash(Kind::Changeset, &encoded);
389+ Ok(Assembled {
390+ changeset,
391+ id,
392+ encoded,
393+ external_list,
394+ })
395+ }
396+}
397+
398+impl Changeset {
399+ /// The canonical encoding.
400+ pub fn encode(&self) -> Vec<u8> {
401+ let mut out = vec![FORMAT];
402+ put_uv(&mut out, self.parents.len() as u64);
403+ for parent in &self.parents {
404+ put_id(&mut out, parent);
405+ }
406+ put_id(&mut out, &self.root);
407+ match &self.changes {
408+ Changes::Inline(changes) => {
409+ out.push(0);
410+ out.extend_from_slice(&encode_change_list(changes));
411+ }
412+ Changes::External { list, count } => {
413+ out.push(1);
414+ put_id(&mut out, list);
415+ put_uv(&mut out, *count);
416+ }
417+ }
418+ self.author.encode(&mut out);
419+ self.committer.encode(&mut out);
420+ put_bytes(&mut out, &self.message);
421+ put_uv(&mut out, self.extras.len() as u64);
422+ for (key, value) in &self.extras {
423+ put_bytes(&mut out, key);
424+ put_bytes(&mut out, value);
425+ }
426+ match &self.git_origin {
427+ None => out.push(0),
428+ Some(id) => {
429+ out.push(1);
430+ put_id(&mut out, id);
431+ }
432+ }
433+ out
434+ }
435+
436+ /// The id of this changeset.
437+ pub fn id(&self) -> ObjectId {
438+ ObjectId::hash(Kind::Changeset, &self.encode())
439+ }
440+
441+ /// Decodes a changeset and checks everything that can be checked without
442+ /// other objects.
443+ pub fn decode(bytes: &[u8]) -> Result<Self, ChangesetError> {
444+ let mut reader = Reader::new(bytes);
445+ let at = reader.position();
446+ if reader.u8()? != FORMAT {
447+ return Err(DecodeError::Invalid {
448+ at,
449+ what: "changeset format",
450+ }
451+ .into());
452+ }
453+ let parent_count = reader.count(32)?;
454+ let mut parents = Vec::with_capacity(parent_count);
455+ for _ in 0..parent_count {
456+ parents.push(reader.id()?);
457+ }
458+ let root = reader.id()?;
459+ let at = reader.position();
460+ let changes = match reader.u8()? {
461+ 0 => {
462+ let start = reader.position();
463+ let changes = read_change_list(&mut reader)?;
464+ let len = reader.position() - start;
465+ if len > MAX_INLINE_CHANGES_BYTES {
466+ return Err(ChangesetError::InlineTooLong(len));
467+ }
468+ Changes::Inline(changes)
469+ }
470+ 1 => Changes::External {
471+ list: reader.id()?,
472+ count: reader.uv()?,
473+ },
474+ _ => {
475+ return Err(DecodeError::Invalid {
476+ at,
477+ what: "change list mode",
478+ }
479+ .into());
480+ }
481+ };
482+ let author = Signature::decode(&mut reader)?;
483+ let committer = Signature::decode(&mut reader)?;
484+ let message = reader.bytes()?.to_vec();
485+ let extra_count = reader.count(2)?;
486+ let mut extras = Vec::with_capacity(extra_count);
487+ for _ in 0..extra_count {
488+ let key = reader.bytes()?.to_vec();
489+ let value = reader.bytes()?.to_vec();
490+ extras.push((key, value));
491+ }
492+ let at = reader.position();
493+ let git_origin = match reader.u8()? {
494+ 0 => None,
495+ 1 => Some(reader.id()?),
496+ _ => {
497+ return Err(DecodeError::Invalid {
498+ at,
499+ what: "git origin flag",
500+ }
501+ .into());
502+ }
503+ };
504+ reader.finish()?;
505+ Ok(Changeset {
506+ parents,
507+ root,
508+ changes,
509+ author,
510+ committer,
511+ message,
512+ extras,
513+ git_origin,
514+ })
515+ }
516+}
517+
518+#[cfg(test)]
519+mod tests {
520+ use super::*;
521+ use crate::tree::build_directory;
522+
523+ fn blob(text: &str) -> ObjectId {
524+ ObjectId::hash(Kind::Blob, text.as_bytes())
525+ }
526+
527+ fn signature() -> Signature {
528+ Signature {
529+ name: b"Ada Lovelace".to_vec(),
530+ email: b"ada@example.org".to_vec(),
531+ seconds: 1_700_000_000,
532+ offset_minutes: 60,
533+ }
534+ }
535+
536+ fn parts(changes: Vec<Change>) -> ChangesetParts {
537+ ChangesetParts {
538+ parents: Vec::new(),
539+ root: build_directory(Vec::new()).unwrap().root(),
540+ changes,
541+ author: signature(),
542+ committer: signature(),
543+ message: b"Initial import\n".to_vec(),
544+ extras: Vec::new(),
545+ git_origin: None,
546+ }
547+ }
548+
549+ fn set(path: &str, text: &str) -> Change {
550+ Change {
551+ path: path.as_bytes().to_vec(),
552+ op: ChangeOp::File {
553+ blob: blob(text),
554+ size: text.len() as u64,
555+ },
556+ }
557+ }
558+
559+ #[test]
560+ fn golden_changeset() {
561+ let assembled = parts(vec![set("README.md", "hello\n"), set("src/lib.rs", "")])
562+ .assemble()
563+ .unwrap();
564+ assert!(assembled.external_list.is_none());
565+ assert_eq!(
566+ assembled.id.to_hex(),
567+ "4f8d49034a95a2938d30d13bee5508100211d04e1c125ef567a0c41c27f777d1"
568+ );
569+ }
570+
571+ #[test]
572+ fn round_trip_with_everything() {
573+ let mut p = parts(vec![
574+ set("b/x", "1"),
575+ Change {
576+ path: b"a".to_vec(),
577+ op: ChangeOp::Delete,
578+ },
579+ Change {
580+ path: b"c".to_vec(),
581+ op: ChangeOp::Gitlink {
582+ commit: GitId::Sha256([7; 32]),
583+ },
584+ },
585+ ]);
586+ p.parents = vec![blob("p1"), blob("p2")];
587+ p.extras = vec![
588+ (b"gpgsig".to_vec(), b"sig".to_vec()),
589+ (b"gpgsig".to_vec(), b"sig".to_vec()),
590+ ];
591+ p.git_origin = Some(blob("raw commit"));
592+ p.author.seconds = -5;
593+ p.committer.offset_minutes = -330;
594+ let assembled = p.assemble().unwrap();
595+ let decoded = Changeset::decode(&assembled.encoded).unwrap();
596+ assert_eq!(decoded, assembled.changeset);
597+ assert_eq!(decoded.encode(), assembled.encoded);
598+ assert_eq!(decoded.id(), assembled.id);
599+ match &decoded.changes {
600+ Changes::Inline(changes) => {
601+ let paths: Vec<&[u8]> = changes.iter().map(|c| c.path.as_slice()).collect();
602+ assert_eq!(paths, [&b"a"[..], b"b/x", b"c"]);
603+ }
604+ Changes::External { .. } => panic!("expected an inline list"),
605+ }
606+ }
607+
608+ #[test]
609+ fn large_lists_go_to_a_blob() {
610+ let changes: Vec<Change> = (0..3000)
611+ .map(|i| set(&format!("dir/file-{i:06}.txt"), "x"))
612+ .collect();
613+ let assembled = parts(changes.clone()).assemble().unwrap();
614+ let (list_id, list) = assembled.external_list.clone().unwrap();
615+ assert_eq!(list_id, ObjectId::hash(Kind::Blob, &list));
616+ assert_eq!(decode_change_list(&list).unwrap(), changes);
617+ assert_eq!(
618+ assembled.changeset.changes,
619+ Changes::External {
620+ list: list_id,
621+ count: 3000
622+ }
623+ );
624+ let decoded = Changeset::decode(&assembled.encoded).unwrap();
625+ assert_eq!(decoded, assembled.changeset);
626+ }
627+
628+ #[test]
629+ fn rejects_bad_lists() {
630+ let duplicate = parts(vec![set("a", "1"), set("a", "2")]).assemble();
631+ assert_eq!(duplicate, Err(ChangesetError::Unsorted { index: 1 }));
632+ let bad_path = parts(vec![set("a/../b", "1")]).assemble();
633+ assert!(matches!(bad_path, Err(ChangesetError::Path { .. })));
634+ let git_dir = parts(vec![set(".git/config", "1")]).assemble();
635+ assert!(matches!(git_dir, Err(ChangesetError::Path { .. })));
636+ let symlink = |path: &str| Change {
637+ path: path.as_bytes().to_vec(),
638+ op: ChangeOp::Symlink {
639+ blob: blob("target"),
640+ size: 6,
641+ },
642+ };
643+ assert_eq!(
644+ parts(vec![symlink("sub/.GITMODULES")]).assemble(),
645+ Err(ChangesetError::SymlinkName(b"sub/.GITMODULES".to_vec()))
646+ );
647+ assert!(
648+ parts(vec![symlink("sub/.gitmodules-notes")])
649+ .assemble()
650+ .is_ok()
651+ );
652+
653+ // An inline list longer than the limit is not canonical.
654+ let changes: Vec<Change> = (0..3000)
655+ .map(|i| set(&format!("dir/file-{i:06}.txt"), "x"))
656+ .collect();
657+ let mut forged = parts(Vec::new()).assemble().unwrap().changeset;
658+ forged.changes = Changes::Inline(changes);
659+ assert!(matches!(
660+ Changeset::decode(&forged.encode()),
661+ Err(ChangesetError::InlineTooLong(_))
662+ ));
663+
664+ let good = parts(vec![set("a", "1")]).assemble().unwrap().encoded;
665+ let mut trailing = good.clone();
666+ trailing.push(0);
667+ assert!(matches!(
668+ Changeset::decode(&trailing),
669+ Err(ChangesetError::Decode(DecodeError::TrailingBytes { .. }))
670+ ));
671+ for cut in 0..good.len() {
672+ assert!(Changeset::decode(&good[..cut]).is_err(), "cut at {cut}");
673+ }
674+ }
675+}
added crates/format/src/codec.rs +331 −0
@@ -0,0 +1,331 @@
1+// SPDX-License-Identifier: Apache-2.0
2+// Copyright (c) 2026 UtopiaIA
3+
4+//! The canonical binary codec shared by every hashed format.
5+//!
6+//! - `uv`: unsigned LEB128, at most 64 bits, always in its shortest form.
7+//! - `sv`: a signed integer, zigzag-mapped and then written as `uv`.
8+//! - `bytes`: a `uv` length followed by that many raw bytes.
9+//!
10+//! The decoder is strict: it rejects overlong integers, integers that do not
11+//! fit in 64 bits, lengths that run past the input, and trailing bytes. Every
12+//! value therefore has exactly one encoding, which is what lets an id stand for
13+//! the value.
14+
15+use core::fmt;
16+
17+use crate::id::ObjectId;
18+
19+/// Why some bytes are not a canonical encoding.
20+#[derive(Clone, Debug, PartialEq, Eq)]
21+pub enum DecodeError {
22+ /// The input ended in the middle of a field that starts at `at`.
23+ UnexpectedEnd { at: usize },
24+ /// The integer at `at` uses more bytes than its shortest form.
25+ NonMinimalInteger { at: usize },
26+ /// The integer at `at` does not fit in 64 bits.
27+ IntegerOverflow { at: usize },
28+ /// The length or count at `at` is larger than the rest of the input.
29+ LengthTooLarge { at: usize },
30+ /// Bytes were left after the last field, starting at `at`.
31+ TrailingBytes { at: usize },
32+ /// The field at `at` holds a value the format does not allow.
33+ Invalid { at: usize, what: &'static str },
34+}
35+
36+impl fmt::Display for DecodeError {
37+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38+ match self {
39+ DecodeError::UnexpectedEnd { at } => {
40+ write!(f, "input ends inside the field at byte {at}")
41+ }
42+ DecodeError::NonMinimalInteger { at } => {
43+ write!(f, "integer at byte {at} is not in its shortest form")
44+ }
45+ DecodeError::IntegerOverflow { at } => {
46+ write!(f, "integer at byte {at} does not fit in 64 bits")
47+ }
48+ DecodeError::LengthTooLarge { at } => {
49+ write!(f, "length at byte {at} runs past the end of the input")
50+ }
51+ DecodeError::TrailingBytes { at } => write!(f, "unexpected bytes from byte {at} on"),
52+ DecodeError::Invalid { at, what } => write!(f, "invalid {what} at byte {at}"),
53+ }
54+ }
55+}
56+
57+impl std::error::Error for DecodeError {}
58+
59+/// Reads canonical fields from a byte slice, front to back.
60+#[derive(Debug)]
61+pub struct Reader<'a> {
62+ buf: &'a [u8],
63+ pos: usize,
64+}
65+
66+impl<'a> Reader<'a> {
67+ /// Starts reading at the beginning of `buf`.
68+ pub fn new(buf: &'a [u8]) -> Self {
69+ Self { buf, pos: 0 }
70+ }
71+
72+ /// Byte offset of the next field.
73+ pub fn position(&self) -> usize {
74+ self.pos
75+ }
76+
77+ /// Bytes not read yet.
78+ pub fn remaining(&self) -> usize {
79+ self.buf.len() - self.pos
80+ }
81+
82+ /// Reads exactly `n` bytes.
83+ pub fn take(&mut self, n: usize) -> Result<&'a [u8], DecodeError> {
84+ if n > self.remaining() {
85+ return Err(DecodeError::UnexpectedEnd { at: self.pos });
86+ }
87+ let out = &self.buf[self.pos..self.pos + n];
88+ self.pos += n;
89+ Ok(out)
90+ }
91+
92+ /// Reads one byte.
93+ pub fn u8(&mut self) -> Result<u8, DecodeError> {
94+ Ok(self.take(1)?[0])
95+ }
96+
97+ /// Reads a fixed-size array.
98+ pub fn array<const N: usize>(&mut self) -> Result<[u8; N], DecodeError> {
99+ let mut out = [0u8; N];
100+ out.copy_from_slice(self.take(N)?);
101+ Ok(out)
102+ }
103+
104+ /// Reads a 32-byte object id.
105+ pub fn id(&mut self) -> Result<ObjectId, DecodeError> {
106+ Ok(ObjectId::from_bytes(self.array()?))
107+ }
108+
109+ /// Reads an unsigned LEB128 integer in its shortest form.
110+ pub fn uv(&mut self) -> Result<u64, DecodeError> {
111+ let at = self.pos;
112+ let mut value = 0u64;
113+ let mut shift = 0u32;
114+ loop {
115+ let byte = self.u8().map_err(|_| DecodeError::UnexpectedEnd { at })?;
116+ let low = u64::from(byte & 0x7f);
117+ if shift == 63 && low > 1 {
118+ return Err(DecodeError::IntegerOverflow { at });
119+ }
120+ value |= low << shift;
121+ if byte & 0x80 == 0 {
122+ if byte == 0 && shift > 0 {
123+ return Err(DecodeError::NonMinimalInteger { at });
124+ }
125+ return Ok(value);
126+ }
127+ shift += 7;
128+ if shift > 63 {
129+ return Err(DecodeError::IntegerOverflow { at });
130+ }
131+ }
132+ }
133+
134+ /// Reads a zigzag-mapped signed integer.
135+ pub fn sv(&mut self) -> Result<i64, DecodeError> {
136+ Ok(unzigzag(self.uv()?))
137+ }
138+
139+ /// Reads a `uv` that must be a length or count, and checks that at least
140+ /// `count × min_item_bytes` bytes remain, so that a forged count can never
141+ /// make the decoder reserve more memory than the input could fill.
142+ pub fn count(&mut self, min_item_bytes: usize) -> Result<usize, DecodeError> {
143+ let at = self.pos;
144+ let n = self.uv()?;
145+ let n = usize::try_from(n).map_err(|_| DecodeError::LengthTooLarge { at })?;
146+ if n.saturating_mul(min_item_bytes) > self.remaining() {
147+ return Err(DecodeError::LengthTooLarge { at });
148+ }
149+ Ok(n)
150+ }
151+
152+ /// Reads `bytes`: a length followed by that many bytes.
153+ pub fn bytes(&mut self) -> Result<&'a [u8], DecodeError> {
154+ let at = self.pos;
155+ let n = self.uv()?;
156+ let n = usize::try_from(n).map_err(|_| DecodeError::LengthTooLarge { at })?;
157+ if n > self.remaining() {
158+ return Err(DecodeError::LengthTooLarge { at });
159+ }
160+ self.take(n)
161+ }
162+
163+ /// Succeeds only if every byte was read.
164+ pub fn finish(self) -> Result<(), DecodeError> {
165+ if self.pos == self.buf.len() {
166+ Ok(())
167+ } else {
168+ Err(DecodeError::TrailingBytes { at: self.pos })
169+ }
170+ }
171+}
172+
173+/// Appends an unsigned LEB128 integer in its shortest form.
174+pub fn put_uv(out: &mut Vec<u8>, mut value: u64) {
175+ loop {
176+ let low = (value & 0x7f) as u8;
177+ value >>= 7;
178+ if value == 0 {
179+ out.push(low);
180+ return;
181+ }
182+ out.push(low | 0x80);
183+ }
184+}
185+
186+/// Appends a zigzag-mapped signed integer.
187+pub fn put_sv(out: &mut Vec<u8>, value: i64) {
188+ put_uv(out, zigzag(value));
189+}
190+
191+/// Appends `bytes`: the length, then the bytes.
192+pub fn put_bytes(out: &mut Vec<u8>, bytes: &[u8]) {
193+ put_uv(out, bytes.len() as u64);
194+ out.extend_from_slice(bytes);
195+}
196+
197+/// Appends a 32-byte object id.
198+pub fn put_id(out: &mut Vec<u8>, id: &ObjectId) {
199+ out.extend_from_slice(id.as_bytes());
200+}
201+
202+/// Number of bytes `put_uv` writes for `value`.
203+pub fn uv_len(value: u64) -> usize {
204+ let bits = 64 - value.leading_zeros() as usize;
205+ bits.div_ceil(7).max(1)
206+}
207+
208+/// Maps signed to unsigned so that small magnitudes stay small: 0, -1, 1, -2, …
209+/// become 0, 1, 2, 3, …
210+pub const fn zigzag(value: i64) -> u64 {
211+ ((value << 1) ^ (value >> 63)) as u64
212+}
213+
214+/// The inverse of [`zigzag`].
215+pub const fn unzigzag(value: u64) -> i64 {
216+ ((value >> 1) as i64) ^ -((value & 1) as i64)
217+}
218+
219+#[cfg(test)]
220+mod tests {
221+ use super::*;
222+
223+ fn uv_bytes(value: u64) -> Vec<u8> {
224+ let mut out = Vec::new();
225+ put_uv(&mut out, value);
226+ out
227+ }
228+
229+ fn read_uv(bytes: &[u8]) -> Result<u64, DecodeError> {
230+ let mut reader = Reader::new(bytes);
231+ let value = reader.uv()?;
232+ reader.finish()?;
233+ Ok(value)
234+ }
235+
236+ #[test]
237+ fn uv_vectors() {
238+ let cases: &[(u64, &[u8])] = &[
239+ (0, &[0x00]),
240+ (1, &[0x01]),
241+ (127, &[0x7f]),
242+ (128, &[0x80, 0x01]),
243+ (300, &[0xac, 0x02]),
244+ (16_383, &[0xff, 0x7f]),
245+ (16_384, &[0x80, 0x80, 0x01]),
246+ (
247+ u64::MAX,
248+ &[0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01],
249+ ),
250+ ];
251+ for (value, bytes) in cases {
252+ assert_eq!(uv_bytes(*value), *bytes, "{value}");
253+ assert_eq!(read_uv(bytes), Ok(*value), "{value}");
254+ assert_eq!(uv_len(*value), bytes.len(), "{value}");
255+ }
256+ }
257+
258+ #[test]
259+ fn uv_rejects_non_canonical() {
260+ assert_eq!(
261+ read_uv(&[0x80, 0x00]),
262+ Err(DecodeError::NonMinimalInteger { at: 0 })
263+ );
264+ assert_eq!(
265+ read_uv(&[0xff, 0x80, 0x00]),
266+ Err(DecodeError::NonMinimalInteger { at: 0 })
267+ );
268+ // Eleven bytes, or a tenth byte above 1, cannot fit in 64 bits.
269+ assert_eq!(
270+ read_uv(&[0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x02]),
271+ Err(DecodeError::IntegerOverflow { at: 0 })
272+ );
273+ assert_eq!(
274+ read_uv(&[
275+ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x81, 0x00
276+ ]),
277+ Err(DecodeError::IntegerOverflow { at: 0 })
278+ );
279+ assert_eq!(read_uv(&[0x80]), Err(DecodeError::UnexpectedEnd { at: 0 }));
280+ assert_eq!(read_uv(&[]), Err(DecodeError::UnexpectedEnd { at: 0 }));
281+ assert_eq!(
282+ read_uv(&[0x01, 0x02]),
283+ Err(DecodeError::TrailingBytes { at: 1 })
284+ );
285+ }
286+
287+ #[test]
288+ fn zigzag_vectors() {
289+ let cases: &[(i64, u64)] = &[
290+ (0, 0),
291+ (-1, 1),
292+ (1, 2),
293+ (-2, 3),
294+ (i64::MAX, u64::MAX - 1),
295+ (i64::MIN, u64::MAX),
296+ ];
297+ for (signed, unsigned) in cases {
298+ assert_eq!(zigzag(*signed), *unsigned);
299+ assert_eq!(unzigzag(*unsigned), *signed);
300+ }
301+ }
302+
303+ #[test]
304+ fn bytes_and_count_guard_lengths() {
305+ let mut out = Vec::new();
306+ put_bytes(&mut out, b"abc");
307+ let mut reader = Reader::new(&out);
308+ assert_eq!(reader.bytes(), Ok(&b"abc"[..]));
309+ reader.finish().unwrap();
310+
311+ // A length past the end of the input.
312+ let mut reader = Reader::new(&[0x05, b'a']);
313+ assert_eq!(reader.bytes(), Err(DecodeError::LengthTooLarge { at: 0 }));
314+
315+ // A count that would need more bytes than remain.
316+ let mut forged = Vec::new();
317+ put_uv(&mut forged, u64::MAX);
318+ let mut reader = Reader::new(&forged);
319+ assert_eq!(reader.count(1), Err(DecodeError::LengthTooLarge { at: 0 }));
320+ }
321+
322+ #[test]
323+ fn uv_round_trips_at_every_boundary() {
324+ for shift in 0..64 {
325+ for value in [(1u64 << shift) - 1, 1u64 << shift, (1u64 << shift) + 1] {
326+ assert_eq!(read_uv(&uv_bytes(value)), Ok(value));
327+ assert_eq!(uv_bytes(value).len(), uv_len(value));
328+ }
329+ }
330+ }
331+}
modified crates/format/src/lib.rs +12 −0
@@ -10,6 +10,18 @@
1010
1111 #![forbid(unsafe_code)]
1212
13+pub mod changeset;
14+pub mod codec;
1315 pub mod id;
16+pub mod name;
17+pub mod tree;
1418
19+pub use changeset::{
20+ Change, ChangeOp, Changes, Changeset, ChangesetError, ChangesetParts, Signature,
21+};
22+pub use codec::DecodeError;
1523 pub use id::{IdHasher, Kind, ObjectId, ParseIdError};
24+pub use name::{NameError, PathError, validate_name, validate_path};
25+pub use tree::{
26+ Directory, Entry, EntryKind, GitId, Node, TreeError, build_directory, read_directory,
27+};
added crates/format/src/name.rs +292 −0
@@ -0,0 +1,292 @@
1+// SPDX-License-Identifier: Apache-2.0
2+// Copyright (c) 2026 UtopiaIA
3+
4+//! Rules for the names that make up paths.
5+//!
6+//! The store accepts nearly any name, about what `git fsck` accepts. It refuses
7+//! names that cannot be one path component, and names that some file system
8+//! would treat as `.braid` or `.git`: a crafted repository could otherwise
9+//! write into the metadata of the checkout that receives it.
10+
11+use core::fmt;
12+
13+use unicode_normalization::UnicodeNormalization;
14+
15+/// Longest name accepted, in bytes.
16+pub const MAX_NAME_BYTES: usize = 4096;
17+
18+/// Directory names that hold version control metadata.
19+const RESERVED: [&[u8]; 2] = [b".braid", b".git"];
20+
21+/// Their 8.3 short-name stems (without the `~N` suffix).
22+const RESERVED_SHORT: [&[u8]; 2] = [b"braid", b"git"];
23+
24+/// Files that git or braid read, and that must therefore never be symlinks.
25+const NO_SYMLINK: [&[u8]; 4] = [
26+ b".gitmodules",
27+ b".gitignore",
28+ b".gitattributes",
29+ b".braidignore",
30+];
31+
32+/// Why a name is not accepted.
33+#[derive(Clone, Debug, PartialEq, Eq)]
34+pub enum NameError {
35+ /// The name is empty.
36+ Empty,
37+ /// The name is longer than [`MAX_NAME_BYTES`].
38+ TooLong(usize),
39+ /// The name contains `/`.
40+ Slash,
41+ /// The name contains a NUL byte.
42+ Nul,
43+ /// The name is `.` or `..`.
44+ DotOrDotDot,
45+ /// Some file system would treat the name as `.braid` or `.git`.
46+ Reserved,
47+}
48+
49+impl fmt::Display for NameError {
50+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
51+ match self {
52+ NameError::Empty => f.write_str("empty name"),
53+ NameError::TooLong(len) => {
54+ write!(f, "name of {len} bytes is longer than {MAX_NAME_BYTES}")
55+ }
56+ NameError::Slash => f.write_str("name contains '/'"),
57+ NameError::Nul => f.write_str("name contains a NUL byte"),
58+ NameError::DotOrDotDot => f.write_str("name is '.' or '..'"),
59+ NameError::Reserved => {
60+ f.write_str("name would be read as .braid or .git on some file system")
61+ }
62+ }
63+ }
64+}
65+
66+impl std::error::Error for NameError {}
67+
68+/// Why a path is not accepted.
69+#[derive(Clone, Debug, PartialEq, Eq)]
70+pub enum PathError {
71+ /// The component at this position (0-based) is not a valid name. An empty
72+ /// component means a leading, trailing or doubled `/`.
73+ Component { index: usize, error: NameError },
74+}
75+
76+impl fmt::Display for PathError {
77+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
78+ match self {
79+ PathError::Component { index, error } => write!(f, "component {index}: {error}"),
80+ }
81+ }
82+}
83+
84+impl std::error::Error for PathError {}
85+
86+/// Checks one name, as stored in a tree.
87+pub fn validate_name(name: &[u8]) -> Result<(), NameError> {
88+ if name.is_empty() {
89+ return Err(NameError::Empty);
90+ }
91+ if name.len() > MAX_NAME_BYTES {
92+ return Err(NameError::TooLong(name.len()));
93+ }
94+ if name.contains(&b'/') {
95+ return Err(NameError::Slash);
96+ }
97+ if name.contains(&0) {
98+ return Err(NameError::Nul);
99+ }
100+ if name == b"." || name == b".." {
101+ return Err(NameError::DotOrDotDot);
102+ }
103+ if is_reserved(name) {
104+ return Err(NameError::Reserved);
105+ }
106+ Ok(())
107+}
108+
109+/// Checks a path: names joined by single `/`, no leading or trailing `/`.
110+pub fn validate_path(path: &[u8]) -> Result<(), PathError> {
111+ for (index, component) in path.split(|byte| *byte == b'/').enumerate() {
112+ validate_name(component).map_err(|error| PathError::Component { index, error })?;
113+ }
114+ Ok(())
115+}
116+
117+/// Whether some file system would treat `name` as `.braid` or `.git`.
118+pub fn is_reserved(name: &[u8]) -> bool {
119+ let folded = fold_for_aliases(name);
120+ RESERVED.contains(&folded.as_slice()) || is_short_name(&folded)
121+}
122+
123+/// Whether `name` must not be a symlink.
124+pub fn forbidden_as_symlink(name: &[u8]) -> bool {
125+ NO_SYMLINK.contains(&fold_for_aliases(name).as_slice())
126+}
127+
128+/// The name as the most forgiving file systems would compare it: without the
129+/// code points HFS+ ignores, in Unicode NFC, lowercased, and without anything
130+/// from the first `:` on (NTFS streams) or trailing dots and spaces (NTFS).
131+///
132+/// Only meant to detect aliases of special names; checkouts use a fold that
133+/// matches the file system they write to.
134+pub fn fold_for_aliases(name: &[u8]) -> Vec<u8> {
135+ let mut folded = match core::str::from_utf8(name) {
136+ Ok(text) => text
137+ .chars()
138+ .filter(|c| !is_hfs_ignorable(*c))
139+ .nfc()
140+ .flat_map(char::to_lowercase)
141+ .collect::<String>()
142+ .into_bytes(),
143+ // A name that is not UTF-8 can only alias an ASCII name byte for byte.
144+ Err(_) => name.to_ascii_lowercase(),
145+ };
146+ if let Some(colon) = folded.iter().position(|byte| *byte == b':') {
147+ folded.truncate(colon);
148+ }
149+ while matches!(folded.last(), Some(b'.' | b' ')) {
150+ folded.pop();
151+ }
152+ folded
153+}
154+
155+/// Code points that HFS+ drops when it compares names.
156+fn is_hfs_ignorable(c: char) -> bool {
157+ matches!(
158+ c,
159+ '\u{200c}'..='\u{200f}' | '\u{202a}'..='\u{202e}' | '\u{206a}'..='\u{206f}' | '\u{feff}'
160+ )
161+}
162+
163+/// `braid~N` or `git~N`: the 8.3 short names NTFS can give `.braid` and `.git`.
164+fn is_short_name(folded: &[u8]) -> bool {
165+ RESERVED_SHORT.iter().any(|stem| {
166+ folded.len() == stem.len() + 2
167+ && folded.starts_with(stem)
168+ && folded[stem.len()] == b'~'
169+ && matches!(folded[stem.len() + 1], b'1'..=b'9')
170+ })
171+}
172+
173+#[cfg(test)]
174+mod tests {
175+ use super::*;
176+
177+ #[test]
178+ fn accepts_ordinary_names() {
179+ for name in [
180+ &b"README.md"[..],
181+ b"src",
182+ b".github",
183+ b".gitkeep",
184+ b".git-blame-ignore-revs",
185+ b"git",
186+ b"braid",
187+ b"...",
188+ b"a b",
189+ b"caf\xc3\xa9",
190+ b"\xff\xfe",
191+ b"git~10",
192+ ] {
193+ assert_eq!(
194+ validate_name(name),
195+ Ok(()),
196+ "{:?}",
197+ String::from_utf8_lossy(name)
198+ );
199+ }
200+ }
201+
202+ #[test]
203+ fn rejects_structural_problems() {
204+ assert_eq!(validate_name(b""), Err(NameError::Empty));
205+ assert_eq!(validate_name(b"a/b"), Err(NameError::Slash));
206+ assert_eq!(validate_name(b"a\0b"), Err(NameError::Nul));
207+ assert_eq!(validate_name(b"."), Err(NameError::DotOrDotDot));
208+ assert_eq!(validate_name(b".."), Err(NameError::DotOrDotDot));
209+ let long = vec![b'a'; MAX_NAME_BYTES + 1];
210+ assert_eq!(
211+ validate_name(&long),
212+ Err(NameError::TooLong(MAX_NAME_BYTES + 1))
213+ );
214+ assert_eq!(validate_name(&long[..MAX_NAME_BYTES]), Ok(()));
215+ }
216+
217+ #[test]
218+ fn rejects_aliases_of_metadata_directories() {
219+ let aliases: &[&str] = &[
220+ ".git",
221+ ".braid",
222+ ".GIT",
223+ ".Braid",
224+ ".git.",
225+ ".git ",
226+ ".git . .",
227+ ".git::$INDEX_ALLOCATION",
228+ ".braid:stream",
229+ "GIT~1",
230+ "git~2",
231+ "BRAID~1",
232+ // HFS+ ignores these code points.
233+ ".g\u{200c}it",
234+ "\u{feff}.git",
235+ ".bra\u{206f}id",
236+ ];
237+ for alias in aliases {
238+ assert_eq!(
239+ validate_name(alias.as_bytes()),
240+ Err(NameError::Reserved),
241+ "{alias:?}"
242+ );
243+ }
244+ }
245+
246+ #[test]
247+ fn unicode_normalisation_is_applied() {
248+ // "é" precomposed and decomposed fold to the same bytes.
249+ assert_eq!(
250+ fold_for_aliases("caf\u{e9}".as_bytes()),
251+ fold_for_aliases("cafe\u{301}".as_bytes())
252+ );
253+ }
254+
255+ #[test]
256+ fn symlink_restrictions() {
257+ assert!(forbidden_as_symlink(b".gitmodules"));
258+ assert!(forbidden_as_symlink(b".GITIGNORE"));
259+ assert!(forbidden_as_symlink(b".braidignore."));
260+ assert!(forbidden_as_symlink(".gitattr\u{200d}ibutes".as_bytes()));
261+ assert!(!forbidden_as_symlink(b"gitmodules"));
262+ assert!(!forbidden_as_symlink(b"README"));
263+ }
264+
265+ #[test]
266+ fn paths() {
267+ assert_eq!(validate_path(b"a"), Ok(()));
268+ assert_eq!(validate_path(b"a/b/c.txt"), Ok(()));
269+ let empty = |index| PathError::Component {
270+ index,
271+ error: NameError::Empty,
272+ };
273+ assert_eq!(validate_path(b""), Err(empty(0)));
274+ assert_eq!(validate_path(b"/a"), Err(empty(0)));
275+ assert_eq!(validate_path(b"a/"), Err(empty(1)));
276+ assert_eq!(validate_path(b"a//b"), Err(empty(1)));
277+ assert_eq!(
278+ validate_path(b"a/.git/config"),
279+ Err(PathError::Component {
280+ index: 1,
281+ error: NameError::Reserved
282+ })
283+ );
284+ assert_eq!(
285+ validate_path(b"a/../b"),
286+ Err(PathError::Component {
287+ index: 1,
288+ error: NameError::DotOrDotDot
289+ })
290+ );
291+ }
292+}
added crates/format/src/tree.rs +737 −0
@@ -0,0 +1,737 @@
1+// SPDX-License-Identifier: Apache-2.0
2+// Copyright (c) 2026 UtopiaIA
3+
4+//! Trees: one directory, stored as a single flat node or, when it is large, as
5+//! a balanced structure of nodes whose boundaries depend only on entry names.
6+//!
7+//! A directory with up to [`MAX_FLAT_ENTRIES`] entries is always one flat node.
8+//! A larger one is split into leaves and internal nodes: walking the sorted
9+//! entries, a node ends after an entry whose name hashes below a threshold
10+//! (once the node holds at least [`MIN_NODE_ENTRIES`]), or when it reaches
11+//! [`MAX_NODE_ENTRIES`]. The same set of entries therefore always gives the
12+//! same nodes and the same root id, whatever order it was edited in, and an
13+//! edit only touches the nodes on its path.
14+
15+use core::fmt;
16+
17+use crate::codec::{DecodeError, Reader, put_bytes, put_id, put_uv};
18+use crate::id::{Kind, ObjectId};
19+use crate::name::{NameError, forbidden_as_symlink, validate_name};
20+
21+/// Format byte of every tree node.
22+pub const FORMAT: u8 = 1;
23+
24+/// A directory with at most this many entries is one flat node.
25+pub const MAX_FLAT_ENTRIES: usize = 1024;
26+
27+/// A node of a split directory only ends on a name boundary once it holds
28+/// at least this many entries or children.
29+pub const MIN_NODE_ENTRIES: usize = 32;
30+
31+/// A node of a split directory never holds more than this many entries or
32+/// children.
33+pub const MAX_NODE_ENTRIES: usize = 512;
34+
35+const SPLIT_CONTEXT: &str = "elffuss-braid 2026 tree-split v1";
36+
37+/// One name in 128 ends a node: 2³² / 128.
38+const SPLIT_THRESHOLD: u32 = 1 << 25;
39+
40+const NODE_FLAT: u8 = 0;
41+const NODE_LEAF: u8 = 1;
42+const NODE_INTERNAL: u8 = 2;
43+
44+/// A git object id, kept for submodules (gitlinks).
45+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
46+pub enum GitId {
47+ /// A SHA-1 id.
48+ Sha1([u8; 20]),
49+ /// A SHA-256 id.
50+ Sha256([u8; 32]),
51+}
52+
53+impl GitId {
54+ /// The raw id bytes.
55+ pub fn as_bytes(&self) -> &[u8] {
56+ match self {
57+ GitId::Sha1(bytes) => bytes,
58+ GitId::Sha256(bytes) => bytes,
59+ }
60+ }
61+
62+ pub(crate) fn encode(&self, out: &mut Vec<u8>) {
63+ match self {
64+ GitId::Sha1(bytes) => {
65+ out.push(1);
66+ out.extend_from_slice(bytes);
67+ }
68+ GitId::Sha256(bytes) => {
69+ out.push(2);
70+ out.extend_from_slice(bytes);
71+ }
72+ }
73+ }
74+
75+ pub(crate) fn decode(reader: &mut Reader<'_>) -> Result<Self, DecodeError> {
76+ let at = reader.position();
77+ match reader.u8()? {
78+ 1 => Ok(GitId::Sha1(reader.array()?)),
79+ 2 => Ok(GitId::Sha256(reader.array()?)),
80+ _ => Err(DecodeError::Invalid {
81+ at,
82+ what: "git id algorithm",
83+ }),
84+ }
85+ }
86+}
87+
88+/// What a directory entry is.
89+#[derive(Clone, Debug, PartialEq, Eq, Hash)]
90+pub enum EntryKind {
91+ /// A regular file.
92+ File { blob: ObjectId, size: u64 },
93+ /// An executable file.
94+ Executable { blob: ObjectId, size: u64 },
95+ /// A symlink; the blob holds its target.
96+ Symlink { blob: ObjectId, size: u64 },
97+ /// A subdirectory.
98+ Tree { tree: ObjectId },
99+ /// A git submodule, pinned to a commit of another repository.
100+ Gitlink { commit: GitId },
101+}
102+
103+impl EntryKind {
104+ /// The one-byte code of this kind in the encoding.
105+ pub const fn code(&self) -> u8 {
106+ match self {
107+ EntryKind::File { .. } => 0,
108+ EntryKind::Executable { .. } => 1,
109+ EntryKind::Symlink { .. } => 2,
110+ EntryKind::Tree { .. } => 3,
111+ EntryKind::Gitlink { .. } => 4,
112+ }
113+ }
114+}
115+
116+/// One entry of a directory.
117+#[derive(Clone, Debug, PartialEq, Eq, Hash)]
118+pub struct Entry {
119+ /// The entry's name, a single path component.
120+ pub name: Vec<u8>,
121+ /// What the entry is.
122+ pub kind: EntryKind,
123+}
124+
125+impl Entry {
126+ fn encode(&self, out: &mut Vec<u8>) {
127+ put_bytes(out, &self.name);
128+ out.push(self.kind.code());
129+ match &self.kind {
130+ EntryKind::File { blob, size }
131+ | EntryKind::Executable { blob, size }
132+ | EntryKind::Symlink { blob, size } => {
133+ put_id(out, blob);
134+ put_uv(out, *size);
135+ }
136+ EntryKind::Tree { tree } => put_id(out, tree),
137+ EntryKind::Gitlink { commit } => commit.encode(out),
138+ }
139+ }
140+
141+ fn decode(reader: &mut Reader<'_>) -> Result<Self, TreeError> {
142+ let name = reader.bytes()?.to_vec();
143+ let at = reader.position();
144+ let kind = match reader.u8()? {
145+ 0 => EntryKind::File {
146+ blob: reader.id()?,
147+ size: reader.uv()?,
148+ },
149+ 1 => EntryKind::Executable {
150+ blob: reader.id()?,
151+ size: reader.uv()?,
152+ },
153+ 2 => EntryKind::Symlink {
154+ blob: reader.id()?,
155+ size: reader.uv()?,
156+ },
157+ 3 => EntryKind::Tree { tree: reader.id()? },
158+ 4 => EntryKind::Gitlink {
159+ commit: GitId::decode(reader)?,
160+ },
161+ _ => {
162+ return Err(TreeError::Decode(DecodeError::Invalid {
163+ at,
164+ what: "entry kind",
165+ }));
166+ }
167+ };
168+ let entry = Entry { name, kind };
169+ validate_entry(&entry)?;
170+ Ok(entry)
171+ }
172+}
173+
174+/// Smallest possible encoded entry: a 1-byte name, a kind and a SHA-1 gitlink.
175+const MIN_ENTRY_BYTES: usize = 1 + 1 + 1 + 1 + 20;
176+
177+/// Smallest possible encoded child reference.
178+const MIN_CHILD_BYTES: usize = 1 + 1 + 32 + 1;
179+
180+/// A reference from an internal node to the node below it.
181+#[derive(Clone, Debug, PartialEq, Eq, Hash)]
182+pub struct Child {
183+ /// Name of the last entry under this child.
184+ pub last_name: Vec<u8>,
185+ /// Id of the child node.
186+ pub node: ObjectId,
187+ /// Number of entries under this child.
188+ pub entry_count: u64,
189+}
190+
191+/// One encoded tree object.
192+#[derive(Clone, Debug, PartialEq, Eq)]
193+pub enum Node {
194+ /// A whole directory of at most [`MAX_FLAT_ENTRIES`] entries.
195+ Flat(Vec<Entry>),
196+ /// A run of entries of a split directory.
197+ Leaf(Vec<Entry>),
198+ /// A run of children of a split directory.
199+ Internal {
200+ /// 1 for the nodes just above the leaves.
201+ level: u8,
202+ /// The nodes below, in name order.
203+ children: Vec<Child>,
204+ },
205+}
206+
207+/// Why a tree is not valid.
208+#[derive(Clone, Debug, PartialEq, Eq)]
209+pub enum TreeError {
210+ /// The bytes are not a canonical encoding.
211+ Decode(DecodeError),
212+ /// An entry name is not valid.
213+ Name { name: Vec<u8>, error: NameError },
214+ /// A name that git or braid reads is a symlink.
215+ SymlinkName(Vec<u8>),
216+ /// Names are not strictly ascending; `index` is the first entry out of order.
217+ Unsorted { index: usize },
218+ /// A node holds more entries or children than allowed, or none.
219+ BadNodeSize { count: usize },
220+ /// A child reference covers no entries.
221+ EmptyChild,
222+ /// A node referenced by a split directory is missing.
223+ MissingNode(ObjectId),
224+ /// The nodes are well-formed but not the canonical split of their entries.
225+ NotCanonical,
226+}
227+
228+impl fmt::Display for TreeError {
229+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
230+ match self {
231+ TreeError::Decode(err) => write!(f, "{err}"),
232+ TreeError::Name { name, error } => {
233+ write!(f, "entry {:?}: {error}", String::from_utf8_lossy(name))
234+ }
235+ TreeError::SymlinkName(name) => write!(
236+ f,
237+ "entry {:?} must not be a symlink",
238+ String::from_utf8_lossy(name)
239+ ),
240+ TreeError::Unsorted { index } => {
241+ write!(f, "entry {index} is out of order or a duplicate")
242+ }
243+ TreeError::BadNodeSize { count } => write!(f, "node holds {count} items"),
244+ TreeError::EmptyChild => f.write_str("child reference covers no entries"),
245+ TreeError::MissingNode(id) => write!(f, "tree node {id} is missing"),
246+ TreeError::NotCanonical => {
247+ f.write_str("nodes are not the canonical split of the directory")
248+ }
249+ }
250+ }
251+}
252+
253+impl std::error::Error for TreeError {}
254+
255+impl From<DecodeError> for TreeError {
256+ fn from(err: DecodeError) -> Self {
257+ TreeError::Decode(err)
258+ }
259+}
260+
261+/// Checks one entry on its own: its name, and the symlink restriction.
262+pub fn validate_entry(entry: &Entry) -> Result<(), TreeError> {
263+ validate_name(&entry.name).map_err(|error| TreeError::Name {
264+ name: entry.name.clone(),
265+ error,
266+ })?;
267+ if matches!(entry.kind, EntryKind::Symlink { .. }) && forbidden_as_symlink(&entry.name) {
268+ return Err(TreeError::SymlinkName(entry.name.clone()));
269+ }
270+ Ok(())
271+}
272+
273+fn check_ascending<'a>(names: impl Iterator<Item = &'a [u8]>) -> Result<(), TreeError> {
274+ let mut previous: Option<&[u8]> = None;
275+ for (index, name) in names.enumerate() {
276+ if previous.is_some_and(|p| p >= name) {
277+ return Err(TreeError::Unsorted { index });
278+ }
279+ previous = Some(name);
280+ }
281+ Ok(())
282+}
283+
284+impl Node {
285+ /// The canonical encoding.
286+ pub fn encode(&self) -> Vec<u8> {
287+ let mut out = vec![FORMAT];
288+ match self {
289+ Node::Flat(entries) | Node::Leaf(entries) => {
290+ out.push(if matches!(self, Node::Flat(_)) {
291+ NODE_FLAT
292+ } else {
293+ NODE_LEAF
294+ });
295+ put_uv(&mut out, entries.len() as u64);
296+ for entry in entries {
297+ entry.encode(&mut out);
298+ }
299+ }
300+ Node::Internal { level, children } => {
301+ out.push(NODE_INTERNAL);
302+ out.push(*level);
303+ put_uv(&mut out, children.len() as u64);
304+ for child in children {
305+ put_bytes(&mut out, &child.last_name);
306+ put_id(&mut out, &child.node);
307+ put_uv(&mut out, child.entry_count);
308+ }
309+ }
310+ }
311+ out
312+ }
313+
314+ /// The id of this node.
315+ pub fn id(&self) -> ObjectId {
316+ ObjectId::hash(Kind::Tree, &self.encode())
317+ }
318+
319+ /// Decodes one node and checks everything that can be checked without
320+ /// the other nodes of its directory.
321+ pub fn decode(bytes: &[u8]) -> Result<Self, TreeError> {
322+ let mut reader = Reader::new(bytes);
323+ let at = reader.position();
324+ if reader.u8()? != FORMAT {
325+ return Err(DecodeError::Invalid {
326+ at,
327+ what: "tree format",
328+ }
329+ .into());
330+ }
331+ let at = reader.position();
332+ let node = match reader.u8()? {
333+ node_type @ (NODE_FLAT | NODE_LEAF) => {
334+ let count = reader.count(MIN_ENTRY_BYTES)?;
335+ let limit = if node_type == NODE_FLAT {
336+ MAX_FLAT_ENTRIES
337+ } else {
338+ MAX_NODE_ENTRIES
339+ };
340+ if count > limit || (node_type == NODE_LEAF && count == 0) {
341+ return Err(TreeError::BadNodeSize { count });
342+ }
343+ let mut entries = Vec::with_capacity(count);
344+ for _ in 0..count {
345+ entries.push(Entry::decode(&mut reader)?);
346+ }
347+ check_ascending(entries.iter().map(|e| e.name.as_slice()))?;
348+ if node_type == NODE_FLAT {
349+ Node::Flat(entries)
350+ } else {
351+ Node::Leaf(entries)
352+ }
353+ }
354+ NODE_INTERNAL => {
355+ let level_at = reader.position();
356+ let level = reader.u8()?;
357+ if level == 0 {
358+ return Err(DecodeError::Invalid {
359+ at: level_at,
360+ what: "internal node level",
361+ }
362+ .into());
363+ }
364+ let count = reader.count(MIN_CHILD_BYTES)?;
365+ if count == 0 || count > MAX_NODE_ENTRIES {
366+ return Err(TreeError::BadNodeSize { count });
367+ }
368+ let mut children = Vec::with_capacity(count);
369+ for _ in 0..count {
370+ let last_name = reader.bytes()?.to_vec();
371+ validate_name(&last_name).map_err(|error| TreeError::Name {
372+ name: last_name.clone(),
373+ error,
374+ })?;
375+ let node = reader.id()?;
376+ let entry_count = reader.uv()?;
377+ if entry_count == 0 {
378+ return Err(TreeError::EmptyChild);
379+ }
380+ children.push(Child {
381+ last_name,
382+ node,
383+ entry_count,
384+ });
385+ }
386+ check_ascending(children.iter().map(|c| c.last_name.as_slice()))?;
387+ Node::Internal { level, children }
388+ }
389+ _ => {
390+ return Err(DecodeError::Invalid {
391+ at,
392+ what: "tree node type",
393+ }
394+ .into());
395+ }
396+ };
397+ reader.finish()?;
398+ Ok(node)
399+ }
400+}
401+
402+/// The encoded nodes of one directory, children before parents. The last
403+/// node is the root, whose id is the directory's id.
404+#[derive(Clone, Debug, PartialEq, Eq)]
405+pub struct Directory {
406+ /// `(id, encoding)` of every node.
407+ pub nodes: Vec<(ObjectId, Vec<u8>)>,
408+}
409+
410+impl Directory {
411+ /// The id of the directory: the id of its root node.
412+ pub fn root(&self) -> ObjectId {
413+ self.nodes
414+ .last()
415+ .map(|(id, _)| *id)
416+ .expect("a directory always has a root node")
417+ }
418+}
419+
420+/// Whether a node ends after an item named `name` that makes its size `count`.
421+fn ends_node(level: u8, name: &[u8], count: usize) -> bool {
422+ if count >= MAX_NODE_ENTRIES {
423+ return true;
424+ }
425+ if count < MIN_NODE_ENTRIES {
426+ return false;
427+ }
428+ let mut hasher = blake3::Hasher::new_derive_key(SPLIT_CONTEXT);
429+ hasher.update(&[level]);
430+ hasher.update(name);
431+ let digest = hasher.finalize();
432+ let head = digest.as_bytes();
433+ u32::from_le_bytes([head[0], head[1], head[2], head[3]]) < SPLIT_THRESHOLD
434+}
435+
436+fn push_node(nodes: &mut Vec<(ObjectId, Vec<u8>)>, node: &Node) -> ObjectId {
437+ let bytes = node.encode();
438+ let id = ObjectId::hash(Kind::Tree, &bytes);
439+ nodes.push((id, bytes));
440+ id
441+}
442+
443+/// Builds the canonical nodes of a directory from its entries, in any order.
444+pub fn build_directory(mut entries: Vec<Entry>) -> Result<Directory, TreeError> {
445+ entries.sort_by(|a, b| a.name.cmp(&b.name));
446+ check_ascending(entries.iter().map(|e| e.name.as_slice()))?;
447+ for entry in &entries {
448+ validate_entry(entry)?;
449+ }
450+
451+ let mut nodes = Vec::new();
452+ if entries.len() <= MAX_FLAT_ENTRIES {
453+ push_node(&mut nodes, &Node::Flat(entries));
454+ return Ok(Directory { nodes });
455+ }
456+
457+ // Leaves.
458+ let total = entries.len();
459+ let mut children = Vec::new();
460+ let mut run = Vec::new();
461+ for (i, entry) in entries.into_iter().enumerate() {
462+ let ends = ends_node(0, &entry.name, run.len() + 1);
463+ run.push(entry);
464+ if ends || i + 1 == total {
465+ let last_name = run
466+ .last()
467+ .map(|e: &Entry| e.name.clone())
468+ .unwrap_or_default();
469+ let entry_count = run.len() as u64;
470+ let node = push_node(&mut nodes, &Node::Leaf(core::mem::take(&mut run)));
471+ children.push(Child {
472+ last_name,
473+ node,
474+ entry_count,
475+ });
476+ }
477+ }
478+
479+ // Internal levels, until one node is left.
480+ let mut level = 1u8;
481+ while children.len() > 1 {
482+ let total = children.len();
483+ let mut parents = Vec::new();
484+ let mut run: Vec<Child> = Vec::new();
485+ for (i, child) in children.into_iter().enumerate() {
486+ let ends = ends_node(level, &child.last_name, run.len() + 1);
487+ run.push(child);
488+ if ends || i + 1 == total {
489+ let last_name = run.last().map(|c| c.last_name.clone()).unwrap_or_default();
490+ let entry_count = run.iter().map(|c| c.entry_count).sum();
491+ let node = push_node(
492+ &mut nodes,
493+ &Node::Internal {
494+ level,
495+ children: core::mem::take(&mut run),
496+ },
497+ );
498+ parents.push(Child {
499+ last_name,
500+ node,
501+ entry_count,
502+ });
503+ }
504+ }
505+ children = parents;
506+ level += 1;
507+ }
508+ Ok(Directory { nodes })
509+}
510+
511+/// Reads every entry of the directory rooted at `root`, fetching nodes through
512+/// `fetch`, and checks that the nodes are exactly the canonical split of those
513+/// entries.
514+pub fn read_directory(
515+ root: ObjectId,
516+ mut fetch: impl FnMut(&ObjectId) -> Option<Vec<u8>>,
517+) -> Result<Vec<Entry>, TreeError> {
518+ let mut entries = Vec::new();
519+ collect(root, &mut fetch, &mut entries, None)?;
520+ if build_directory(entries.clone())?.root() != root {
521+ return Err(TreeError::NotCanonical);
522+ }
523+ Ok(entries)
524+}
525+
526+fn collect(
527+ id: ObjectId,
528+ fetch: &mut impl FnMut(&ObjectId) -> Option<Vec<u8>>,
529+ entries: &mut Vec<Entry>,
530+ expected_level: Option<u8>,
531+) -> Result<(), TreeError> {
532+ let bytes = fetch(&id).ok_or(TreeError::MissingNode(id))?;
533+ if ObjectId::hash(Kind::Tree, &bytes) != id {
534+ return Err(TreeError::NotCanonical);
535+ }
536+ match (Node::decode(&bytes)?, expected_level) {
537+ (Node::Flat(found), None) => entries.extend(found),
538+ (Node::Leaf(found), Some(0)) => entries.extend(found),
539+ (Node::Internal { level, children }, expected) if expected.is_none_or(|e| e == level) => {
540+ for child in children {
541+ collect(child.node, fetch, entries, Some(level - 1))?;
542+ }
543+ }
544+ _ => return Err(TreeError::NotCanonical),
545+ }
546+ Ok(())
547+}
548+
549+#[cfg(test)]
550+mod tests {
551+ use super::*;
552+
553+ fn blob(text: &str) -> ObjectId {
554+ ObjectId::hash(Kind::Blob, text.as_bytes())
555+ }
556+
557+ fn file(name: &str, text: &str) -> Entry {
558+ Entry {
559+ name: name.as_bytes().to_vec(),
560+ kind: EntryKind::File {
561+ blob: blob(text),
562+ size: text.len() as u64,
563+ },
564+ }
565+ }
566+
567+ fn many(n: usize, content: &str) -> Vec<Entry> {
568+ (0..n).map(|i| file(&format!("f{i:05}"), content)).collect()
569+ }
570+
571+ #[test]
572+ fn empty_tree() {
573+ let dir = build_directory(Vec::new()).unwrap();
574+ assert_eq!(dir.nodes.len(), 1);
575+ assert_eq!(dir.nodes[0].1, vec![FORMAT, NODE_FLAT, 0]);
576+ assert_eq!(
577+ dir.root().to_hex(),
578+ "3136b0f18562ee73b840ea348c54ae3c7e97e4cc3e547ea9dd03fa1cd8b384cf",
579+ "the empty tree id is part of format v1"
580+ );
581+ }
582+
583+ #[test]
584+ fn small_tree_golden() {
585+ let entries = vec![
586+ file("README.md", "hello\n"),
587+ Entry {
588+ name: b"run.sh".to_vec(),
589+ kind: EntryKind::Executable {
590+ blob: blob("#!/bin/sh\n"),
591+ size: 10,
592+ },
593+ },
594+ Entry {
595+ name: b"latest".to_vec(),
596+ kind: EntryKind::Symlink {
597+ blob: blob("README.md"),
598+ size: 9,
599+ },
600+ },
601+ Entry {
602+ name: b"src".to_vec(),
603+ kind: EntryKind::Tree {
604+ tree: build_directory(Vec::new()).unwrap().root(),
605+ },
606+ },
607+ Entry {
608+ name: b"vendor".to_vec(),
609+ kind: EntryKind::Gitlink {
610+ commit: GitId::Sha1([0x11; 20]),
611+ },
612+ },
613+ ];
614+ let dir = build_directory(entries).unwrap();
615+ assert_eq!(dir.nodes.len(), 1);
616+ assert_eq!(
617+ dir.root().to_hex(),
618+ "a6c6d54bb7663d576e8f7a702e0670927e22098d6c15c10475e06b51dc3d8c1b"
619+ );
620+ }
621+
622+ #[test]
623+ fn flat_up_to_the_limit_then_split() {
624+ let flat = build_directory(many(MAX_FLAT_ENTRIES, "x")).unwrap();
625+ assert_eq!(flat.nodes.len(), 1);
626+ assert!(matches!(
627+ Node::decode(&flat.nodes[0].1).unwrap(),
628+ Node::Flat(_)
629+ ));
630+
631+ let split = build_directory(many(MAX_FLAT_ENTRIES + 1, "x")).unwrap();
632+ assert!(split.nodes.len() >= 3);
633+ assert!(matches!(
634+ Node::decode(&split.nodes.last().unwrap().1).unwrap(),
635+ Node::Internal { .. }
636+ ));
637+ }
638+
639+ #[test]
640+ fn large_tree_golden() {
641+ let dir = build_directory(many(5000, "x")).unwrap();
642+ assert_eq!(
643+ dir.root().to_hex(),
644+ "2c88a412664c1fd862c3487e1313a045a20fe4f7bdeaf1bb71e08564edc7dcce"
645+ );
646+ assert_eq!(dir.nodes.len(), LARGE_TREE_NODES);
647+ }
648+
649+ const LARGE_TREE_NODES: usize = 30;
650+
651+ #[test]
652+ fn read_back_and_reject_non_canonical_splits() {
653+ let entries = many(3000, "x");
654+ let dir = build_directory(entries.clone()).unwrap();
655+ let store: std::collections::HashMap<ObjectId, Vec<u8>> =
656+ dir.nodes.iter().cloned().collect();
657+ let read = read_directory(dir.root(), |id| store.get(id).cloned()).unwrap();
658+ assert_eq!(read, entries);
659+
660+ // The same entries packed into one oversized flat node are refused.
661+ let fake = Node::Flat(entries.clone());
662+ let bytes = fake.encode();
663+ assert!(matches!(
664+ Node::decode(&bytes),
665+ Err(TreeError::BadNodeSize { .. })
666+ ));
667+
668+ // Two leaves split at the wrong place, under a hand-made root.
669+ let left = Node::Leaf(entries[..100].to_vec());
670+ let right = Node::Leaf(entries[100..500].to_vec());
671+ let root = Node::Internal {
672+ level: 1,
673+ children: vec![
674+ Child {
675+ last_name: entries[99].name.clone(),
676+ node: left.id(),
677+ entry_count: 100,
678+ },
679+ Child {
680+ last_name: entries[499].name.clone(),
681+ node: right.id(),
682+ entry_count: 400,
683+ },
684+ ],
685+ };
686+ let store: std::collections::HashMap<ObjectId, Vec<u8>> = [&left, &right, &root]
687+ .iter()
688+ .map(|n| (n.id(), n.encode()))
689+ .collect();
690+ assert_eq!(
691+ read_directory(root.id(), |id| store.get(id).cloned()),
692+ Err(TreeError::NotCanonical)
693+ );
694+ }
695+
696+ #[test]
697+ fn decode_rejects_bad_input() {
698+ let unsorted = Node::Flat(vec![file("b", "1"), file("a", "2")]).encode();
699+ assert_eq!(
700+ Node::decode(&unsorted),
701+ Err(TreeError::Unsorted { index: 1 })
702+ );
703+ let duplicate = Node::Flat(vec![file("a", "1"), file("a", "2")]).encode();
704+ assert_eq!(
705+ Node::decode(&duplicate),
706+ Err(TreeError::Unsorted { index: 1 })
707+ );
708+ let reserved = Node::Flat(vec![file(".GIT", "1")]).encode();
709+ assert!(matches!(
710+ Node::decode(&reserved),
711+ Err(TreeError::Name { .. })
712+ ));
713+ let symlink = Node::Flat(vec![Entry {
714+ name: b".gitmodules".to_vec(),
715+ kind: EntryKind::Symlink {
716+ blob: blob("x"),
717+ size: 1,
718+ },
719+ }])
720+ .encode();
721+ assert!(matches!(
722+ Node::decode(&symlink),
723+ Err(TreeError::SymlinkName(_))
724+ ));
725+ let mut trailing = Node::Flat(vec![file("a", "1")]).encode();
726+ trailing.push(0);
727+ assert!(matches!(
728+ Node::decode(&trailing),
729+ Err(TreeError::Decode(DecodeError::TrailingBytes { .. }))
730+ ));
731+ assert!(Node::decode(&[]).is_err());
732+ assert!(Node::decode(&[2, 0, 0]).is_err());
733+ assert!(Node::decode(&[FORMAT, 9]).is_err());
734+ assert!(Node::decode(&[FORMAT, NODE_LEAF, 0]).is_err());
735+ assert!(Node::decode(&[FORMAT, NODE_INTERNAL, 0, 0]).is_err());
736+ }
737+}
added crates/format/tests/properties.rs +264 −0
@@ -0,0 +1,264 @@
1+// SPDX-License-Identifier: Apache-2.0
2+// Copyright (c) 2026 UtopiaIA
3+
4+//! Property tests: every encoding is canonical, and a directory's nodes depend
5+//! only on its set of entries.
6+
7+use std::collections::{BTreeMap, HashMap};
8+
9+use braid_format::codec::{Reader, put_sv, put_uv};
10+use braid_format::tree::{MAX_FLAT_ENTRIES, MAX_NODE_ENTRIES};
11+use braid_format::{
12+ Change, ChangeOp, Changeset, ChangesetParts, Entry, EntryKind, GitId, Kind, Node, ObjectId,
13+ Signature, build_directory, read_directory, validate_name,
14+};
15+use proptest::prelude::*;
16+
17+fn object_id() -> impl Strategy<Value = ObjectId> {
18+ any::<[u8; 32]>().prop_map(ObjectId::from_bytes)
19+}
20+
21+fn git_id() -> impl Strategy<Value = GitId> {
22+ prop_oneof![
23+ any::<[u8; 20]>().prop_map(GitId::Sha1),
24+ any::<[u8; 32]>().prop_map(GitId::Sha256),
25+ ]
26+}
27+
28+/// Names from a small alphabet, so that sets collide and sort interestingly,
29+/// plus arbitrary Unicode; anything invalid is filtered out.
30+fn name() -> impl Strategy<Value = Vec<u8>> {
31+ prop_oneof![
32+ "[a-c.][a-c0-2.]{0,6}".prop_map(String::into_bytes),
33+ "\\PC{1,6}".prop_map(String::into_bytes),
34+ ]
35+ .prop_filter("valid name", |n| validate_name(n).is_ok())
36+}
37+
38+fn entry_kind() -> impl Strategy<Value = EntryKind> {
39+ prop_oneof![
40+ (object_id(), any::<u64>()).prop_map(|(blob, size)| EntryKind::File { blob, size }),
41+ (object_id(), any::<u64>()).prop_map(|(blob, size)| EntryKind::Executable { blob, size }),
42+ object_id().prop_map(|tree| EntryKind::Tree { tree }),
43+ git_id().prop_map(|commit| EntryKind::Gitlink { commit }),
44+ ]
45+}
46+
47+fn entries(max: usize) -> impl Strategy<Value = Vec<Entry>> {
48+ prop::collection::btree_map(name(), entry_kind(), 0..max).prop_map(|map: BTreeMap<_, _>| {
49+ map.into_iter()
50+ .map(|(name, kind)| Entry { name, kind })
51+ .collect()
52+ })
53+}
54+
55+/// Many distinct names, to exercise split directories.
56+fn wide_entries() -> impl Strategy<Value = Vec<Entry>> {
57+ (MAX_FLAT_ENTRIES - 10..6000usize, any::<u64>()).prop_map(|(n, seed)| {
58+ (0..n)
59+ .map(|i| Entry {
60+ name: format!("n{:x}-{i}", seed.wrapping_mul(i as u64 + 1) % 9973).into_bytes(),
61+ kind: EntryKind::File {
62+ blob: ObjectId::hash(Kind::Blob, &i.to_le_bytes()),
63+ size: i as u64,
64+ },
65+ })
66+ .collect()
67+ })
68+}
69+
70+fn signature() -> impl Strategy<Value = Signature> {
71+ (
72+ prop::collection::vec(any::<u8>(), 0..20),
73+ prop::collection::vec(any::<u8>(), 0..20),
74+ any::<i64>(),
75+ any::<i64>(),
76+ )
77+ .prop_map(|(name, email, seconds, offset_minutes)| Signature {
78+ name,
79+ email,
80+ seconds,
81+ offset_minutes,
82+ })
83+}
84+
85+fn change_op() -> impl Strategy<Value = ChangeOp> {
86+ prop_oneof![
87+ Just(ChangeOp::Delete),
88+ (object_id(), any::<u64>()).prop_map(|(blob, size)| ChangeOp::File { blob, size }),
89+ (object_id(), any::<u64>()).prop_map(|(blob, size)| ChangeOp::Symlink { blob, size }),
90+ git_id().prop_map(|commit| ChangeOp::Gitlink { commit }),
91+ ]
92+}
93+
94+fn changeset_parts() -> impl Strategy<Value = ChangesetParts> {
95+ (
96+ prop::collection::vec(object_id(), 0..4),
97+ object_id(),
98+ prop::collection::btree_map(
99+ prop::collection::vec(name(), 1..4).prop_map(|parts| parts.join(&b'/')),
100+ change_op(),
101+ 0..20,
102+ ),
103+ signature(),
104+ signature(),
105+ prop::collection::vec(any::<u8>(), 0..64),
106+ prop::collection::vec(
107+ (
108+ prop::collection::vec(any::<u8>(), 0..8),
109+ prop::collection::vec(any::<u8>(), 0..8),
110+ ),
111+ 0..4,
112+ ),
113+ prop::option::of(object_id()),
114+ )
115+ .prop_map(
116+ |(parents, root, changes, author, committer, message, extras, git_origin)| {
117+ ChangesetParts {
118+ parents,
119+ root,
120+ changes: changes
121+ .into_iter()
122+ .map(|(path, op)| Change { path, op })
123+ .collect(),
124+ author,
125+ committer,
126+ message,
127+ extras,
128+ git_origin,
129+ }
130+ },
131+ )
132+}
133+
134+fn node_sizes(nodes: &[(ObjectId, Vec<u8>)]) -> Vec<usize> {
135+ nodes
136+ .iter()
137+ .map(|(_, bytes)| match Node::decode(bytes).unwrap() {
138+ Node::Flat(e) | Node::Leaf(e) => e.len(),
139+ Node::Internal { children, .. } => children.len(),
140+ })
141+ .collect()
142+}
143+
144+proptest! {
145+ #[test]
146+ fn integers_round_trip(u in any::<u64>(), s in any::<i64>()) {
147+ let mut out = Vec::new();
148+ put_uv(&mut out, u);
149+ put_sv(&mut out, s);
150+ let mut reader = Reader::new(&out);
151+ prop_assert_eq!(reader.uv().unwrap(), u);
152+ prop_assert_eq!(reader.sv().unwrap(), s);
153+ prop_assert!(reader.finish().is_ok());
154+ }
155+
156+ #[test]
157+ fn small_directories_round_trip(entries in entries(40)) {
158+ let dir = build_directory(entries.clone()).unwrap();
159+ prop_assert_eq!(dir.nodes.len(), 1);
160+ let (id, bytes) = &dir.nodes[0];
161+ let node = Node::decode(bytes).unwrap();
162+ prop_assert_eq!(&node.encode(), bytes);
163+ prop_assert_eq!(node.id(), *id);
164+ prop_assert_eq!(node, Node::Flat(entries));
165+ }
166+
167+ #[test]
168+ fn directory_ignores_input_order(mut entries in entries(40), seed in any::<u64>()) {
169+ let sorted = build_directory(entries.clone()).unwrap();
170+ let n = entries.len().max(1);
171+ entries.rotate_left((seed as usize) % n);
172+ entries.reverse();
173+ prop_assert_eq!(build_directory(entries).unwrap(), sorted);
174+ }
175+
176+ #[test]
177+ fn decoders_never_panic(bytes in prop::collection::vec(any::<u8>(), 0..300)) {
178+ // Whatever the bytes, decoding either fails or round-trips exactly.
179+ if let Ok(node) = Node::decode(&bytes) {
180+ prop_assert_eq!(node.encode(), bytes.clone());
181+ }
182+ if let Ok(changeset) = Changeset::decode(&bytes) {
183+ prop_assert_eq!(changeset.encode(), bytes);
184+ }
185+ }
186+
187+ #[test]
188+ fn changesets_round_trip(parts in changeset_parts()) {
189+ let assembled = parts.assemble().unwrap();
190+ let decoded = Changeset::decode(&assembled.encoded).unwrap();
191+ prop_assert_eq!(&decoded, &assembled.changeset);
192+ prop_assert_eq!(decoded.encode(), assembled.encoded);
193+ prop_assert_eq!(decoded.id(), assembled.id);
194+ }
195+}
196+
197+proptest! {
198+ #![proptest_config(ProptestConfig::with_cases(24))]
199+
200+ #[test]
201+ fn split_directories_are_canonical(entries in wide_entries(), seed in any::<u64>()) {
202+ let mut sorted = entries.clone();
203+ sorted.sort_by(|a, b| a.name.cmp(&b.name));
204+ sorted.dedup_by(|a, b| a.name == b.name);
205+ let dir = build_directory(sorted.clone()).unwrap();
206+
207+ // Every node decodes and re-encodes to itself.
208+ for (id, bytes) in &dir.nodes {
209+ let node = Node::decode(bytes).unwrap();
210+ prop_assert_eq!(&node.encode(), bytes);
211+ prop_assert_eq!(node.id(), *id);
212+ }
213+
214+ // Size limits: nothing above the maximum, and a split directory is
215+ // never stored flat.
216+ let sizes = node_sizes(&dir.nodes);
217+ prop_assert!(sizes.iter().all(|s| *s <= MAX_NODE_ENTRIES.max(MAX_FLAT_ENTRIES)));
218+ if sorted.len() > MAX_FLAT_ENTRIES {
219+ prop_assert!(dir.nodes.len() >= 3);
220+ prop_assert!(sizes.iter().all(|s| *s <= MAX_NODE_ENTRIES));
221+ }
222+
223+ // Reading the nodes back gives the entries and passes the canonical check.
224+ let store: HashMap<ObjectId, Vec<u8>> = dir.nodes.iter().cloned().collect();
225+ prop_assert_eq!(read_directory(dir.root(), |id| store.get(id).cloned()).unwrap(), sorted.clone());
226+
227+ // Boundaries depend on names only: new contents, same node sizes.
228+ let recontent: Vec<Entry> = sorted
229+ .iter()
230+ .map(|e| Entry {
231+ name: e.name.clone(),
232+ kind: EntryKind::File {
233+ blob: ObjectId::hash(Kind::Blob, &seed.to_le_bytes()),
234+ size: seed,
235+ },
236+ })
237+ .collect();
238+ prop_assert_eq!(node_sizes(&build_directory(recontent).unwrap().nodes), sizes.clone());
239+
240+ // Removing one entry keeps every leaf that ends before it: the scan up
241+ // to there is unchanged, so an edit never rewrites earlier leaves.
242+ if sorted.len() > MAX_FLAT_ENTRIES + 1 {
243+ let victim = (seed as usize) % sorted.len();
244+ let mut smaller = sorted.clone();
245+ let removed = smaller.remove(victim);
246+ let after_leaves = leaves(&build_directory(smaller).unwrap().nodes);
247+ for (last, id) in leaves(&dir.nodes) {
248+ if last < removed.name {
249+ prop_assert!(after_leaves.iter().any(|(_, a)| *a == id));
250+ }
251+ }
252+ }
253+ }
254+}
255+
256+fn leaves(nodes: &[(ObjectId, Vec<u8>)]) -> Vec<(Vec<u8>, ObjectId)> {
257+ nodes
258+ .iter()
259+ .filter_map(|(id, bytes)| match Node::decode(bytes).unwrap() {
260+ Node::Leaf(e) => Some((e.last().unwrap().name.clone(), *id)),
261+ _ => None,
262+ })
263+ .collect()
264+}
added docs/spec/check_vectors.py +156 −0
@@ -0,0 +1,156 @@
1+#!/usr/bin/env python3
2+# SPDX-License-Identifier: Apache-2.0
3+# Copyright (c) 2026 UtopiaIA
4+"""Recomputes the golden vectors of format-v1.md from the document alone.
5+
6+This is a second, independent implementation of the hashed formats, written
7+from the specification and not from the Rust code. It needs the reference
8+BLAKE3 tool, b3sum (`cargo install b3sum`), on the PATH.
9+
10+ python3 docs/spec/check_vectors.py
11+"""
12+import subprocess
13+import sys
14+
15+
16+def b3(context, payload):
17+ out = subprocess.run(["b3sum", "--derive-key", context, "--no-names"],
18+ input=payload, capture_output=True, check=True)
19+ return bytes.fromhex(out.stdout.decode().strip())
20+
21+
22+def blob_id(data):
23+ return b3("elffuss-braid 2026 blob v1", data)
24+
25+
26+def tree_id(data):
27+ return b3("elffuss-braid 2026 tree v1", data)
28+
29+
30+def changeset_id(data):
31+ return b3("elffuss-braid 2026 changeset v1", data)
32+
33+
34+def uv(n):
35+ out = bytearray()
36+ while True:
37+ low = n & 0x7F
38+ n >>= 7
39+ if n == 0:
40+ out.append(low)
41+ return bytes(out)
42+ out.append(low | 0x80)
43+
44+
45+def sv(n):
46+ return uv(((n << 1) ^ (n >> 63)) & ((1 << 64) - 1))
47+
48+
49+def bstr(b):
50+ return uv(len(b)) + b
51+
52+
53+def entry(name, kind, *fields):
54+ out = bstr(name) + bytes([kind])
55+ if kind in (0, 1, 2):
56+ out += fields[0] + uv(fields[1])
57+ elif kind == 3:
58+ out += fields[0]
59+ elif kind == 4:
60+ out += bytes([fields[0]]) + fields[1]
61+ return out
62+
63+
64+def flat(entries):
65+ entries = sorted(entries, key=lambda e: e[0])
66+ return bytes([1, 0]) + uv(len(entries)) + b"".join(entry(*e) for e in entries)
67+
68+
69+def split_ends(level, name, count):
70+ if count >= 512:
71+ return True
72+ if count < 32:
73+ return False
74+ h = b3("elffuss-braid 2026 tree-split v1", bytes([level]) + name)
75+ return int.from_bytes(h[:4], "little") < (1 << 25)
76+
77+
78+def split_directory(entries):
79+ """Returns the ids of all nodes of a directory of more than 1024 entries."""
80+ entries = sorted(entries, key=lambda e: e[0])
81+ nodes, children, run = [], [], []
82+ for i, e in enumerate(entries):
83+ ends = split_ends(0, e[0], len(run) + 1)
84+ run.append(e)
85+ if ends or i + 1 == len(entries):
86+ body = bytes([1, 1]) + uv(len(run)) + b"".join(entry(*x) for x in run)
87+ nid = tree_id(body)
88+ nodes.append(nid)
89+ children.append((run[-1][0], nid, len(run)))
90+ run = []
91+ level = 1
92+ while len(children) > 1:
93+ parents, run = [], []
94+ for i, child in enumerate(children):
95+ ends = split_ends(level, child[0], len(run) + 1)
96+ run.append(child)
97+ if ends or i + 1 == len(children):
98+ body = bytes([1, 2, level]) + uv(len(run)) + b"".join(
99+ bstr(c[0]) + c[1] + uv(c[2]) for c in run)
100+ nid = tree_id(body)
101+ nodes.append(nid)
102+ parents.append((run[-1][0], nid, sum(c[2] for c in run)))
103+ run = []
104+ children = parents
105+ level += 1
106+ return nodes
107+
108+
109+EXPECTED = {
110+ "empty tree": "3136b0f18562ee73b840ea348c54ae3c7e97e4cc3e547ea9dd03fa1cd8b384cf",
111+ "small tree": "a6c6d54bb7663d576e8f7a702e0670927e22098d6c15c10475e06b51dc3d8c1b",
112+ "large tree": "2c88a412664c1fd862c3487e1313a045a20fe4f7bdeaf1bb71e08564edc7dcce",
113+ "changeset": "4f8d49034a95a2938d30d13bee5508100211d04e1c125ef567a0c41c27f777d1",
114+}
115+
116+
117+def main():
118+ got = {}
119+ empty_id = tree_id(flat([]))
120+ got["empty tree"] = empty_id
121+
122+ got["small tree"] = tree_id(flat([
123+ (b"README.md", 0, blob_id(b"hello\n"), 6),
124+ (b"run.sh", 1, blob_id(b"#!/bin/sh\n"), 10),
125+ (b"latest", 2, blob_id(b"README.md"), 9),
126+ (b"src", 3, empty_id),
127+ (b"vendor", 4, 1, bytes([0x11] * 20)),
128+ ]))
129+
130+ x = blob_id(b"x")
131+ large = split_directory([(f"f{i:05}".encode(), 0, x, 1) for i in range(5000)])
132+ got["large tree"] = large[-1]
133+
134+ changes = sorted([
135+ (b"README.md", 1, blob_id(b"hello\n"), 6),
136+ (b"src/lib.rs", 1, blob_id(b""), 0),
137+ ])
138+ change_list = uv(len(changes)) + b"".join(
139+ bstr(p) + bytes([op]) + bid + uv(size) for p, op, bid, size in changes)
140+ sig = bstr(b"Ada Lovelace") + bstr(b"ada@example.org") + sv(1_700_000_000) + sv(60)
141+ changeset = (bytes([1]) + uv(0) + empty_id + bytes([0]) + change_list + sig + sig
142+ + bstr(b"Initial import\n") + uv(0) + bytes([0]))
143+ got["changeset"] = changeset_id(changeset)
144+
145+ ok = True
146+ for name, expected in EXPECTED.items():
147+ match = got[name].hex() == expected
148+ ok &= match
149+ print(f"{'ok ' if match else 'FAIL'} {name}: {got[name].hex()}")
150+ print(f"large tree nodes: {len(large)} (expected 30)")
151+ ok &= len(large) == 30
152+ sys.exit(0 if ok else 1)
153+
154+
155+if __name__ == "__main__":
156+ main()
modified docs/spec/format-v1.md +51 −10
@@ -1,9 +1,17 @@
11 # Braid format v1
22
3-**Status: draft.** Sections marked *implemented* exist in code and are pinned by
4-golden vectors in the tests. Everything else is the design that milestone 1
5-implements. The format freezes when milestone 1 closes; after that, any change
6-to hashed bytes needs a new format version.
3+**Status: frozen.** Sections 1 to 5 (ids, the codec, trees, changesets and
4+names) are implemented in `crates/format` and frozen: any change to hashed bytes
5+needs a new format version. Sections 6 and 7 describe the git mapping and the
6+on-disk storage, which are not hashed and can still change.
7+
8+Every golden vector below is pinned by the Rust tests and recomputed by
9+[`check_vectors.py`](check_vectors.py), a second implementation written from
10+this document alone. It needs the reference `b3sum` tool:
11+
12+```bash
13+python3 docs/spec/check_vectors.py
14+```
715
816 This document covers what is **hashed**: ids, trees, changesets and names. How
917 the store keeps objects on disk (records, indexes, compression, deltas, chunks)
@@ -108,9 +116,21 @@
108116 `H(level, name) = BLAKE3-derive-key("elffuss-braid 2026 tree-split v1", u8 level ‖ name)`.
109117
110118 Boundaries depend only on names, so changing a file's content never moves them,
111-and an edit only rewrites the nodes on its path. An incremental update must
112-always produce the same bytes as building the directory from scratch; the tests
113-check this for random edit sequences.
119+and an edit never rewrites the leaves before it. Any way of updating a directory
120+must produce exactly the nodes of building it from scratch.
121+
122+A reader checks a split directory by collecting its entries and building them
123+again: the root must come out identical. A flat node may hold at most 1,024
124+entries, a leaf or internal node at least 1 and at most 512, and an internal
125+node's children must be one level below it.
126+
127+Golden vectors:
128+
129+| Tree | Id |
130+|---|---|
131+| empty (`01 00 00`) | `3136b0f18562ee73b840ea348c54ae3c7e97e4cc3e547ea9dd03fa1cd8b384cf` |
132+| small: `README.md` (file, `hello\n`), `latest` (symlink to `README.md`), `run.sh` (executable, `#!/bin/sh\n`), `src` (the empty tree), `vendor` (SHA-1 gitlink, twenty `11` bytes) | `a6c6d54bb7663d576e8f7a702e0670927e22098d6c15c10475e06b51dc3d8c1b` |
133+| large: 5,000 files `f00000` … `f04999`, each the one-byte blob `x`; 30 nodes | `2c88a412664c1fd862c3487e1313a045a20fe4f7bdeaf1bb71e08564edc7dcce` |
114134
115135 ## 4. Changesets
116136
@@ -147,9 +167,12 @@
147167 compared against the empty tree.
148168 - Changes are per file. A directory replaced by a file is a delete for every
149169 file below it plus one set for the new file.
150-- The list is stored inline when its encoding is at most 64 KiB, and as a
151- separate blob otherwise, so a huge import does not make every history walk
152- read a huge object.
170+- A symlink cannot take a name that must not be a symlink (section 5).
171+- The list is stored inline when its encoding (`uv n, n × change`) is at most
172+ 64 KiB, and otherwise as a blob holding exactly that encoding, so a huge
173+ import does not make every history walk read a huge object. A decoder rejects
174+ an inline list over the limit; the store rejects an external list that would
175+ have fit inline.
153176 - **Admission check.** A store accepts a changeset only if applying its change
154177 list to `parent[0]`'s root tree yields exactly `root_tree`, every referenced
155178 object is present, and every parent was already accepted. The check costs
@@ -160,6 +183,24 @@
160183 git, so export can reproduce the commit bit for bit. The reference is part of
161184 the hash.
162185
186+Golden vector: no parents; root = the empty tree; two changes, `README.md`
187+set to the file `hello\n` (6 bytes) and `src/lib.rs` set to the empty file;
188+author and committer `Ada Lovelace <ada@example.org>` at second 1,700,000,000
189+with offset +60; message `Initial import\n`; no extras; no git origin.
190+
191+```
192+01 00 3136b0f18562ee73b840ea348c54ae3c7e97e4cc3e547ea9dd03fa1cd8b384cf
193+00 02 09 524541444d452e6d64 01 6acd5cdf880a325d2df716699943aae586ad77d54fb2ed0c5a3f53c76fa56f89 06
194+ 0a 7372632f6c69622e7273 01 ff9c212a7ef64fa38f0c411b3a68d523a20fd197ee3ba03fa4a44b7c5e99c958 00
195+0c 416461204c6f76656c616365 0f 616461406578616d706c652e6f7267 80c49fd50c 78
196+0c 416461204c6f76656c616365 0f 616461406578616d706c652e6f7267 80c49fd50c 78
197+0f 496e697469616c20696d706f72740a
198+00
199+00
200+```
201+
202+Id: `4f8d49034a95a2938d30d13bee5508100211d04e1c125ef567a0c41c27f777d1`.
203+
163204 ## 5. Names
164205
165206 The store is permissive, close to what `git fsck` accepts; checkouts are
added fuzz/Cargo.lock +147 −0
@@ -0,0 +1,147 @@
1+# This file is automatically @generated by Cargo.
2+# It is not intended for manual editing.
3+version = 4
4+
5+[[package]]
6+name = "arbitrary"
7+version = "1.5.0"
8+source = "registry+https://github.com/rust-lang/crates.io-index"
9+checksum = "3bc62ac97cc33321f50863d514c3bc38a453947a8f9e781137e47c7401020aed"
10+
11+[[package]]
12+name = "arrayvec"
13+version = "0.7.8"
14+source = "registry+https://github.com/rust-lang/crates.io-index"
15+checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56"
16+
17+[[package]]
18+name = "blake3"
19+version = "1.8.7"
20+source = "registry+https://github.com/rust-lang/crates.io-index"
21+checksum = "6d9e454fc11f76977dc803893aff6304ed33d6a26efae8696573bea74baa27ae"
22+dependencies = [
23+ "arrayvec",
24+ "cc",
25+ "cfg-if",
26+ "constant_time_eq",
27+ "cpufeatures",
28+]
29+
30+[[package]]
31+name = "cc"
32+version = "1.8.0"
33+source = "registry+https://github.com/rust-lang/crates.io-index"
34+checksum = "6651c9ed80effdc7db0ff72512157f901af5e3549e341e24b1dd4887d836d838"
35+dependencies = [
36+ "find-msvc-tools",
37+ "jobserver",
38+ "libc",
39+ "shlex",
40+]
41+
42+[[package]]
43+name = "cfg-if"
44+version = "1.0.5"
45+source = "registry+https://github.com/rust-lang/crates.io-index"
46+checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
47+
48+[[package]]
49+name = "constant_time_eq"
50+version = "0.4.2"
51+source = "registry+https://github.com/rust-lang/crates.io-index"
52+checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b"
53+
54+[[package]]
55+name = "cpufeatures"
56+version = "0.3.1"
57+source = "registry+https://github.com/rust-lang/crates.io-index"
58+checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566"
59+dependencies = [
60+ "libc",
61+]
62+
63+[[package]]
64+name = "elffuss-braid-format"
65+version = "0.0.1"
66+dependencies = [
67+ "blake3",
68+ "unicode-normalization",
69+]
70+
71+[[package]]
72+name = "elffuss-braid-fuzz"
73+version = "0.0.0"
74+dependencies = [
75+ "elffuss-braid-format",
76+ "libfuzzer-sys",
77+]
78+
79+[[package]]
80+name = "find-msvc-tools"
81+version = "0.1.14"
82+source = "registry+https://github.com/rust-lang/crates.io-index"
83+checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484"
84+
85+[[package]]
86+name = "getrandom"
87+version = "0.4.3"
88+source = "registry+https://github.com/rust-lang/crates.io-index"
89+checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
90+dependencies = [
91+ "cfg-if",
92+ "libc",
93+ "r-efi",
94+]
95+
96+[[package]]
97+name = "jobserver"
98+version = "0.1.35"
99+source = "registry+https://github.com/rust-lang/crates.io-index"
100+checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3"
101+dependencies = [
102+ "getrandom",
103+ "libc",
104+]
105+
106+[[package]]
107+name = "libc"
108+version = "0.2.190"
109+source = "registry+https://github.com/rust-lang/crates.io-index"
110+checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78"
111+
112+[[package]]
113+name = "libfuzzer-sys"
114+version = "0.4.13"
115+source = "registry+https://github.com/rust-lang/crates.io-index"
116+checksum = "a9fd2f41a1cba099f79a0b6b6c35656cf7c03351a7bae8ff0f28f25270f929d2"
117+dependencies = [
118+ "arbitrary",
119+ "cc",
120+]
121+
122+[[package]]
123+name = "r-efi"
124+version = "6.0.0"
125+source = "registry+https://github.com/rust-lang/crates.io-index"
126+checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
127+
128+[[package]]
129+name = "shlex"
130+version = "2.0.1"
131+source = "registry+https://github.com/rust-lang/crates.io-index"
132+checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
133+
134+[[package]]
135+name = "tinyvec"
136+version = "1.13.3"
137+source = "registry+https://github.com/rust-lang/crates.io-index"
138+checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee"
139+
140+[[package]]
141+name = "unicode-normalization"
142+version = "0.1.25"
143+source = "registry+https://github.com/rust-lang/crates.io-index"
144+checksum = "5fd4f6878c9cb28d874b009da9e8d183b5abc80117c40bbd187a1fde336be6e8"
145+dependencies = [
146+ "tinyvec",
147+]
added fuzz/Cargo.toml +37 −0
@@ -0,0 +1,37 @@
1+[package]
2+name = "elffuss-braid-fuzz"
3+version = "0.0.0"
4+edition = "2024"
5+license = "Apache-2.0"
6+publish = false
7+
8+[package.metadata]
9+cargo-fuzz = true
10+
11+[workspace]
12+members = ["."]
13+
14+[dependencies]
15+libfuzzer-sys = "0.4"
16+braid-format = { package = "elffuss-braid-format", path = "../crates/format" }
17+
18+[[bin]]
19+name = "decode_tree"
20+path = "fuzz_targets/decode_tree.rs"
21+test = false
22+doc = false
23+bench = false
24+
25+[[bin]]
26+name = "decode_changeset"
27+path = "fuzz_targets/decode_changeset.rs"
28+test = false
29+doc = false
30+bench = false
31+
32+[[bin]]
33+name = "names"
34+path = "fuzz_targets/names.rs"
35+test = false
36+doc = false
37+bench = false
added fuzz/fuzz_targets/decode_changeset.rs +20 −0
@@ -0,0 +1,20 @@
1+// SPDX-License-Identifier: Apache-2.0
2+// Copyright (c) 2026 UtopiaIA
3+
4+//! A changeset, or an external change list, either fails to decode or
5+//! re-encodes to exactly its input.
6+
7+#![no_main]
8+
9+use braid_format::Changeset;
10+use braid_format::changeset::{decode_change_list, encode_change_list};
11+use libfuzzer_sys::fuzz_target;
12+
13+fuzz_target!(|data: &[u8]| {
14+ if let Ok(changeset) = Changeset::decode(data) {
15+ assert_eq!(changeset.encode(), data);
16+ }
17+ if let Ok(changes) = decode_change_list(data) {
18+ assert_eq!(encode_change_list(&changes), data);
19+ }
20+});
added fuzz/fuzz_targets/decode_tree.rs +15 −0
@@ -0,0 +1,15 @@
1+// SPDX-License-Identifier: Apache-2.0
2+// Copyright (c) 2026 UtopiaIA
3+
4+//! A tree node either fails to decode or re-encodes to exactly its input.
5+
6+#![no_main]
7+
8+use braid_format::Node;
9+use libfuzzer_sys::fuzz_target;
10+
11+fuzz_target!(|data: &[u8]| {
12+ if let Ok(node) = Node::decode(data) {
13+ assert_eq!(node.encode(), data);
14+ }
15+});
added fuzz/fuzz_targets/names.rs +25 −0
@@ -0,0 +1,25 @@
1+// SPDX-License-Identifier: Apache-2.0
2+// Copyright (c) 2026 UtopiaIA
3+
4+//! Name rules never panic, and agree with each other: a valid name is a valid
5+//! one-component path, and an alias of a metadata directory is never valid.
6+
7+#![no_main]
8+
9+use braid_format::name::{fold_for_aliases, is_reserved, validate_name, validate_path};
10+use libfuzzer_sys::fuzz_target;
11+
12+fuzz_target!(|data: &[u8]| {
13+ let folded = fold_for_aliases(data);
14+ let valid = validate_name(data).is_ok();
15+ if valid {
16+ assert!(validate_path(data).is_ok());
17+ assert!(!is_reserved(data));
18+ let mut nested = b"dir/".to_vec();
19+ nested.extend_from_slice(data);
20+ assert!(validate_path(&nested).is_ok());
21+ }
22+ if folded == b".git" || folded == b".braid" {
23+ assert!(!valid);
24+ }
25+});