navid/veins / commit
28c08ad11cdd
Navid M <navidmomtahen@gmail.com> · 2026-11-25
parents: 50c2dfe55599
Browse files at this commit · Download source
--- /dev/null+++ b/docs/test-vectors/M0.adoc@@ -0,0 +1,255 @@+= vein Format Test Vectors: Milestone 0+:revnumber: 1+:revdate: 2026-11-25++This document publishes the format-version-1 test vectors for milestone M0:+BLAKE3, canonical varints, FastCDC chunk boundaries, object IDs and bodies,+and the pack/index container. They were generated with an independent Python+implementation using the reference `blake3` package and are checked by+`vn selftest`.++Object IDs use the domain separator from the specification:++[source,text]+----+object_id = BLAKE3("vein/1" 0x00 || type_byte || body)+type_byte: chunk=1 blob=2 tree=3 commit=4 conflict=5 operation=6 view=7+----++The hex encodings below are lowercase and contain no separators. Integer+fields are little-endian.++== BLAKE3++[cols="1,2,2",options="header"]+|===+| Input | Bytes | BLAKE3-256++| empty | (none) | `af1349b9f5f9a1a6a0404dea36dcc9499bcb25c9adc112b7cc9a93cae41f3262`+| `abc` | `616263` | `6437b3ac38465133ffb63b75273a8db548c558465d79db03fd359c6cd5bd9d85`+| `hello world` | `68656c6c6f20776f726c64` | `d74981efa70a0c880b8d8c1985d075dbcbf679b99a5f9914e5aaf96b831a9e24`+|===++Chunker test input (used below):++[source,text]+----+length = 300000+seed = 2+byte[i] = (i * 31 + seed * 17) mod 251+----++Chunking that input produces exactly two chunks:++[cols="1,2,2",options="header"]+|===+| Chunk | Length | Object ID++| 0 | `262144` | `a6a4efd6c6330d328e0a3e2a97fb6202771433ffeeea099a93f8df08399b44fd`+| 1 | `37856` | `4c899670c3ec130e9ce03b5061d2593c2fa4f66661c6285f470e57dc65284444`+|===++The manifest for this file is a single leaf node (form 1) with those two+entries. Its blob ID is:++[source,text]+----+34bb8e7c00665b61c882fe1cae0a51a44d6ad1719fd44a1b22c991ae6a3c24bc+----++== FastCDC gear table++`docs/test-vectors/fastcdc_gear.txt` contains the 256 frozen `u64` entries.+Each entry is derived reproducibly:++[source,text]+----+gear[i] = u64le( BLAKE3("vein/fastcdc/gear/v1" || u8(i))[0..8] )+i = 0..255+----++For convenience, the BLAKE3 of the concatenated 2048-byte little-endian gear+table is:++[source,text]+----+52097d05a1f8eefb70604af851826bea02cf3f47f46aa129a661d630a40972da+----++Parameters: minimum 16 KiB, average 64 KiB, maximum 256 KiB, normalization+level 2. The rolling hash is `fp = (fp >> 1) + gear[byte]` (wrapping `u64`).+A boundary is taken when `fp & 0x3ffff == 0` before the average size and+`fp & 0x3fff == 0` from the average size onward, never before 16 KiB and never+past 256 KiB.++== Canonical varints++[cols="1,2",options="header"]+|===+| Value | Encoding++| 0 | `00`+| 127 | `7f`+| 128 | `80 01`+| 300 | `ac 02`+| 18446744073709551615 | `ff ff ff ff ff ff ff ff ff 01`+|===++A decoder rejects a multi-byte varint whose final group is zero, any encoding+longer than ten bytes, and any tenth byte other than `00` or `01`.++== Object bodies and IDs++[cols="1,2,2,2",options="header"]+|===+| Object | Body hex | ID | Notes++| empty tree | `00` | `01fd6e74c2454903e76762c71e9f22f7418e5d36f6149c48eeee734ec2e3dc41` | empty list+| inline blob `hello` | `000568656c6c6f` | `aecaf09bed6d5bd166cf9f24e88f73081460ec292f4a5eeb7daf4a1078e33d7c` | form 0 + bytes+|===++The following vectors use these three inline blobs:++[source,text]+----+base = "base" -> 000462617365 -> c11596e0f11881620de9b26e54c4c1233e4d9545c09b7a677f0011121a9b56b6+ours = "ours" -> 00046f757273 -> a77d538ccdf102fc33a4f20dfd0a67e9aa16a996bee763f2a14a3fd512d20e75+theirs = "theirs" -> 0006746865697273 -> 4a1f7bff6488363e0902d1c71bb7eb514bcee359ca4fcd2fb3099e152389275f+----++=== Conflict++Two file adds (`ours`, `theirs`) and one file remove (`base`):++[source,text]+----+body = 02+ 01 || ours_id+ 01 || theirs_id+ 01+ 01 || base_id+id = d6d530d1e90142531d26d6db8489b0c42654b312d27b56f74b45d97f2b00e7a9+----++Full body hex:++[source,text]+----+0201a77d538ccdf102fc33a4f20dfd0a67e9aa16a996bee763f2a14a3fd512d20e75014a1f7bff6488363e0902d1c71bb7eb514bcee359ca4fcd2fb3099e152389275f0101c11596e0f11881620de9b26e54c4c1233e4d9545c09b7a677f0011121a9b56b6+----++=== Commit++Fields: version 1, no parents, root tree = empty tree,+change ID = `0b0c0d0e0f101112131415161718191a`,+author = committer = `Alice <alice@example.com>` at 1700000000 +0000,+message `initial commit`, `renames_state = 1`, no renames, no extra headers.++[source,text]+----+body = 0100+ 01fd6e74c2454903e76762c71e9f22f7418e5d36f6149c48eeee734ec2e3dc41+ 0b0c0d0e0f101112131415161718191a+ 05416c696365 11616c696365406578616d706c652e636f6d 00f153650000000000 0000+ 05416c696365 11616c696365406578616d706c652e636f6d 00f153650000000000 0000+ 0e696e697469616c20636f6d6d6974+ 01 00 00+id = c6a60eba55e527a7b746aee77e66fc5e8e60ef31c5c407d57eaceaeececebb3c+----++Full body hex:++[source,text]+----+010001fd6e74c2454903e76762c71e9f22f7418e5d36f6149c48eeee734ec2e3dc410b0c0d0e0f101112131415161718191a05416c69636511616c696365406578616d706c652e636f6d00f1536500000000000005416c69636511616c696365406578616d706c652e636f6d00f153650000000000000e696e697469616c20636f6d6d6974010000+----++=== View++heads = `[commit]`; bookmark `main` resolves to `[commit]`; no tags or+remote refs; working copy `default` at `commit`.++[source,text]+----+body = 01 || commit_id+ 01 || 046d61696e || 01 || 01 || commit_id || 00+ 00+ 00+ 01 || 0764656661756c74 || commit_id+id = 9ba517b0693bd2016b9662f18fb54ca0ceaadc2ab08c4d87d9c4c9e42e689eed+----++Full body hex:++[source,text]+----+01c6a60eba55e527a7b746aee77e66fc5e8e60ef31c5c407d57eaceaeececebb3c01046d61696e0101c6a60eba55e527a7b746aee77e66fc5e8e60ef31c5c407d57eaceaeececebb3c000000010764656661756c74c6a60eba55e527a7b746aee77e66fc5e8e60ef31c5c407d57eaceaeececebb3c+----++=== Operation++No parents; view above; start = end = 1700000000000 +0000; hostname `host`,+username `alice`, description `selftest operation`; no tags.++[source,text]+----+body = 00 || view_id+ 0068e5cf8b01000000 0000+ 0068e5cf8b01000000 0000+ 04686f7374 05616c696365 1273656c6674657374206f7065726174696f6e+ 00+id = 99a9dea611815d7320e8481495227bf62e8a224ec873f3cd1daca5b4e2ece4f1+----++Full body hex:++[source,text]+----+009ba517b0693bd2016b9662f18fb54ca0ceaadc2ab08c4d87d9c4c9e42e689eed0068e5cf8b01000000000068e5cf8b010000000004686f737405616c6963651273656c6674657374206f7065726174696f6e00+----++== Pack and index++A pack containing exactly the empty tree object above, stored uncompressed+(compression byte 0), is 85 bytes:++[source,text]+----+magic 56504b31+version 01000000+count 0100000000000000+record tree_id (32 bytes)+ type_byte 03+ compression 00+ raw_length 01+ stored_length 01+ body 00+trailer 294c1017488cc29fd32a67b299e998e7d995f5636ef245e1a5bc47be5c1e1042+----++Full pack hex:++[source,text]+----+56504b3101000000010000000000000001fd6e74c2454903e76762c71e9f22f7418e5d36f6149c48eeee734ec2e3dc410300010100294c1017488cc29fd32a67b299e998e7d995f5636ef245e1a5bc47be5c1e1042+----++Its index is 1136 bytes. The index contains the fanout, sorted IDs, the+record offset (16), the pack trailer, and the index trailer. Instead of+reproducing 1136 bytes here, the published checks are:++[cols="1,2",options="header"]+|===+| Property | Value++| Length | `1136`+| BLAKE3 of the complete index | `64bae9db19aa5bf84e4fe72e9cfe38e9563c5baa04abb4a4ca887dbdc94e4b1a`+| Index trailer (last 32 bytes) | `786a72638bd8cfe021cc57f54977ff76ed0e760f48e787e7735cbf9f571f4f9e`+| Record offset | `16`+|===++== Verification++`vn selftest` checks every vector in this document, including the exact pack+bytes and the index checksum, and then runs `vn fsck` on a repository+constructed from the vectors.--- /dev/null+++ b/docs/test-vectors/fastcdc_gear.txt@@ -0,0 +1,260 @@+# vein format 1 FastCDC gear table+# gear[i] = u64le(BLAKE3("vein/fastcdc/gear/v1" || u8(i))[0..8])+# 256 entries, one per line, lowercase hexadecimal++5c4a1ae8bc697bc4+404c2fabb73cc047+d3182b34b91a5105+2f6a7a0e10c9a4e9+7547bc4d5b634d0a+23466e59c4b9b389+5e59b19eea3c566a+bac21e55adbf2486+7664aaaf965fcad9+82a61ba3f60574e4+f271f8fa19825daa+0178ec62a70d4219+8a7476f57c1ac5e7+87100c1da58f4225+a3094e45c27e8d72+9a4b8c66691e4b65+01ca246131e5cf43+67082475db706bc6+1e8ff56368a8a554+529004a71bcce301+08e485f89622934f+35784d339932308f+118506e540737be6+a01129f8a140b6bc+fe34955d89fe9c22+e798e7847dcfcd55+f5ed1a81775e5907+c1008c76de665582+cdb70a32b89ff73e+2053279d659f92c0+fb6f25ff149156d2+bbd7cd25542da950+0f795883ab7b0b58+63c9ad4618799824+86758361be3505a2+d0654221203a895a+fc553b7a897060a3+63f30f39088f12b5+1dbbfdb329090dc8+034777bfbda53269+765653f19e19bd5f+12f29bbb5ce1edde+71ed901844f83c6f+b5bab6d75be81227+0df63d3a03b97926+1e5f7fd1a792c82b+7b443971b934bae4+6bc634b7e6eda850+55a65ff08f4a349f+450786016bd046a3+74224c0fd123c0b1+7bfe7a2f975a97b6+5a79f2287ea6d79e+f5249768011b01b8+85247fee784c6164+efaa92326ed3cffc+83e65683edb9ce2a+93c1beaf37c773d8+a613c1f3e59cf6a3+4e53fb579208a3b6+41a478e2ea3a5add+e954507d5f9f528e+a67ee92c34dab874+4fde76eb0b7836c9+0a1d48b4c6aa6b0e+73acd9b67c53c8fe+e7ae8a73f3532a5c+d65989cf5a86b2bb+6cc0caad82f1d784+14c3a111475499f5+515264dfff947d17+350bb4dd5de7b8fe+86fd36770e8a2e36+b0a45b7862f061ed+6bcab5ddfb78481e+7be29762aa52548a+e8ba251664ffc0a6+46b724ec15fe280f+49a3948b86c10650+8728d203182a056f+77e609499e68119d+fa3dea8f23253491+ad1d2671404a08d3+5d1a0bad3e7b7ed2+77340fe7e9f8c5ba+942c81cdf24a0167+167c54a7c493f85e+1664dccbcebc4b22+a61b572d4ad878b8+8b9af023f8602c9f+e7b928217e4811cd+129037e9fd549c7f+61ebe7e42502e4be+0a1ee930ea49fb3b+615fc103e28c8e0a+1f73c58f94a72da1+5689e070f5399d98+e30fe38ef1ad4366+2a593e06370b77d5+3043c337e1854347+e5d72faa615d110c+4038bd291c593240+2ab2bfa552d4b375+8d552f184d7f1bf5+f5797da702a9b9e6+e746797066c7d4ae+9ded398ec8b444ad+1677250cc1263ed7+cd387dfff99848c8+76c8e17e7e3c51c7+88957499ab90cd0b+61e1f2ed44d22926+c67759e92332d47a+20a21f589906abba+cbc97c04dc3600ad+f7c85c33e41fa6a4+1097084d6ec2bba1+9fb02d6d6bf6bf94+be491ed9c83c51e2+a2e98c363d6c67a2+9bec27f58f3b5414+194ac1cb82e2d4ab+0064c87914d677a6+cc73278ab09622b6+8defa41c9b8b9b51+536cf2c4aa196ece+604a6f8528d890f5+284a26063447d249+be70f37289b5497c+06ddcd30daa6a54f+bfb15004943d67fb+62c1f2bb4bf0265a+abe4fe049ba8fd65+20af090e344a0185+416fb2ef6fee28fc+f60d926eacf379b3+53610e6411d45e23+f6fb37c66ba64597+42bf7a59192fe853+c04446e8b297e0f2+82f1f4d862e3ad59+36ba938e2525ee17+49142470e54f7798+4dfebe5f4e61d2bc+15f8c7f7f38338d2+4f36f36937336521+fff70db1621739c8+77768d16df7f7308+55e4ad3f457a73b9+89fe259e513d73ef+1e087e74e73661ad+6c8c61983b203db0+be4846ae96db0e56+97fb0e4e2ec84ad6+f6a841d652558edc+6c8c5a1c2b137937+9f93197506451b99+3234216f7492d666+0969310ecbc88bc6+1f38f4918779c317+fb9d10f0c3a4c23d+b89b140d8f11c5be+10decb1f791bebae+8009d5919e8262f3+9f0cedd8d7d130ab+d14db528d87ee2db+4c180eba3157ac53+6c8897a62e2830a2+46e03299b3b35cf0+e113872493896b19+f1209451f7a4ff94+b939749bf938eebc+b16291a34e66e625+007182e94e603784+b1ae9121fa1a1d1b+6ec222ddf28dca0c+28854d8b1e655115+6332ac9c0d1199a2+365fdd7aeebe647e+0fd7033c86765869+6c516b8859c8bb01+46c24f980413490f+f867fb37bb76dea9+892d78d1aa3f9fcb+cd175fb5a96963ed+5f617cb58fbc8a77+4df29395bddc578d+7d69552224bb6149+3584177015ff325b+816acc8a1c352448+449c10951bca892e+adc4d1fcef7ff534+64d0275a80e466a4+402f692c29a12441+eec7a5bf7941d5d0+5f166583c2601ed5+3b6838dd02fe672f+ccedf39242f8c018+07d8c86783c02ffc+af49620443a23682+d91abe9b213695a2+69163f8bf62b1b7c+e31b2e1d8310913f+0c3d7e22dfc2d09c+756b39a23e62c096+cc2687b10d550a4c+5b6b449b793b7ae4+1b860384dc8e65e7+df57565c73e4c5f8+5ad5f2b6fc9d0ed3+86b2d2094d589220+1db728b73e4dcef6+e2a136a5157f2ca3+08d4b194366445ae+da7f156e2e85d3a9+6c3d56f62df389e9+d4874f9387cb7964+a514cb3f14f74eed+1f37e5ff29d299ee+ea7429deb1b71032+963db43d9b95b0aa+582b6be2902ffc67+2e926ea8a00af35d+92093f9d25126fab+344f7c282e4122ec+87ff7054daeb429b+c49f0e4726d146b9+e0773071e66e17e5+b345dfdb70eee881+9d8e2b9bedc39423+3ebf8325c8ecd78b+9a226652626286c4+96edb25817f1138e+cbb693398017b173+786633d49e99af60+b225db9832e7d8df+4cec56b4202c7d7f+18c8278d6ff7825d+ed46971bf16adef4+522c06f1fa3978df+8d40437999463947+c8959f60eb0d27ad+b9a089058f480f80+215482f345e3c2d5+f91c64d2b1b525b9+b68bd03968c728fa+8b12cebebc865819+6d60b167f805c0d4+40d773d869517dc2+db50fd3858eb7ee6+5af4344ac6a899c7+b055dc42b7329b9b+2314a1c54ecfe1c7+0eaeed2e3c60c346+fe5614b9ebe6329b+8592445ff13752f9--- /dev/null+++ b/src/src/chunking/fastcdc.sx@@ -0,0 +1,78 @@+/// FastCDC content-defined chunking with normalized chunking (level 2).+///+/// Parameters are fixed by the format:+/// minimum 16 KiB, average 64 KiB, maximum 256 KiB, normalization 2.+///+/// The rolling hash consumes a byte as `(fp >> 1) + gear[byte]` (wrapping+/// u64). A boundary is taken when the low bits of the hash are zero, using+/// the stricter mask before the average size and the looser mask after it.++val gear = use("gear.sx")+val lists = use("../core/lists.sx")++pub val MIN_SIZE: usize = 16384+pub val AVG_SIZE: usize = 65536+pub val MAX_SIZE: usize = 262144+pub val NORMALIZATION: usize = 2++val MASK_S: u64 = 0x3ffff+val MASK_L: u64 = 0x3fff++fn gear_at(c: u8) u64 = {+ val o = @get(gear.GEAR, c as usize)+ if o is some v {+ return v+ }+ return 0+}++fn min_usize(a: usize, b: usize) usize = {+ if a < b {+ return a+ }+ return b+}++/// Return the length of the next chunk at `data`, given that at least+/// `len` bytes remain. The result is in `1..=min(len, MAX_SIZE)`.+pub fn next_len(data: ref u8, len: usize) usize = {+ pre {+ progress: len > 0+ }+ if len <= MIN_SIZE {+ return len+ }+ val limit: usize = min_usize(len, MAX_SIZE)+ val normal: usize = min_usize(AVG_SIZE, limit)+ val fp: mut u64 = 0+ val i: mut usize = MIN_SIZE+ for i < normal {+ val c: u8 = trust @load8(@ptradd(data, i as i64))+ fp = (fp >> 1) + gear_at(c)+ if (fp & MASK_S) == 0 {+ return i + 1+ }+ i = i + 1+ }+ for i < limit {+ val c2: u8 = trust @load8(@ptradd(data, i as i64))+ fp = (fp >> 1) + gear_at(c2)+ if (fp & MASK_L) == 0 {+ return i + 1+ }+ i = i + 1+ }+ return limit+}++/// Split a byte span into chunk lengths.+pub fn split(data: ref u8, len: usize) list[usize] = {+ val out: mut list[usize] = lists.new[usize]()+ val off: mut usize = 0+ for off < len {+ val n: usize = next_len(trust @ptradd(data, off as i64), len - off)+ @append(out, n)+ off = off + n+ }+ return out+}--- /dev/null+++ b/src/src/chunking/gear.sx@@ -0,0 +1,75 @@+/// FastCDC gear table for vein format version 1.+///+/// The 256 entries are derived deterministically, so that independent+/// implementations can reproduce them:+///+/// gear[i] = u64le(BLAKE3("vein/fastcdc/gear/v1" || u8(i))[0..8])+///+/// The table is frozen for format version 1. Changing it changes every chunk+/// boundary and therefore every chunk, blob, and commit ID.+val GEAR: [256]u64 = [+ 0x5c4a1ae8bc697bc4, 0x404c2fabb73cc047, 0xd3182b34b91a5105, 0x2f6a7a0e10c9a4e9,+ 0x7547bc4d5b634d0a, 0x23466e59c4b9b389, 0x5e59b19eea3c566a, 0xbac21e55adbf2486,+ 0x7664aaaf965fcad9, 0x82a61ba3f60574e4, 0xf271f8fa19825daa, 0x0178ec62a70d4219,+ 0x8a7476f57c1ac5e7, 0x87100c1da58f4225, 0xa3094e45c27e8d72, 0x9a4b8c66691e4b65,+ 0x01ca246131e5cf43, 0x67082475db706bc6, 0x1e8ff56368a8a554, 0x529004a71bcce301,+ 0x08e485f89622934f, 0x35784d339932308f, 0x118506e540737be6, 0xa01129f8a140b6bc,+ 0xfe34955d89fe9c22, 0xe798e7847dcfcd55, 0xf5ed1a81775e5907, 0xc1008c76de665582,+ 0xcdb70a32b89ff73e, 0x2053279d659f92c0, 0xfb6f25ff149156d2, 0xbbd7cd25542da950,+ 0x0f795883ab7b0b58, 0x63c9ad4618799824, 0x86758361be3505a2, 0xd0654221203a895a,+ 0xfc553b7a897060a3, 0x63f30f39088f12b5, 0x1dbbfdb329090dc8, 0x034777bfbda53269,+ 0x765653f19e19bd5f, 0x12f29bbb5ce1edde, 0x71ed901844f83c6f, 0xb5bab6d75be81227,+ 0x0df63d3a03b97926, 0x1e5f7fd1a792c82b, 0x7b443971b934bae4, 0x6bc634b7e6eda850,+ 0x55a65ff08f4a349f, 0x450786016bd046a3, 0x74224c0fd123c0b1, 0x7bfe7a2f975a97b6,+ 0x5a79f2287ea6d79e, 0xf5249768011b01b8, 0x85247fee784c6164, 0xefaa92326ed3cffc,+ 0x83e65683edb9ce2a, 0x93c1beaf37c773d8, 0xa613c1f3e59cf6a3, 0x4e53fb579208a3b6,+ 0x41a478e2ea3a5add, 0xe954507d5f9f528e, 0xa67ee92c34dab874, 0x4fde76eb0b7836c9,+ 0x0a1d48b4c6aa6b0e, 0x73acd9b67c53c8fe, 0xe7ae8a73f3532a5c, 0xd65989cf5a86b2bb,+ 0x6cc0caad82f1d784, 0x14c3a111475499f5, 0x515264dfff947d17, 0x350bb4dd5de7b8fe,+ 0x86fd36770e8a2e36, 0xb0a45b7862f061ed, 0x6bcab5ddfb78481e, 0x7be29762aa52548a,+ 0xe8ba251664ffc0a6, 0x46b724ec15fe280f, 0x49a3948b86c10650, 0x8728d203182a056f,+ 0x77e609499e68119d, 0xfa3dea8f23253491, 0xad1d2671404a08d3, 0x5d1a0bad3e7b7ed2,+ 0x77340fe7e9f8c5ba, 0x942c81cdf24a0167, 0x167c54a7c493f85e, 0x1664dccbcebc4b22,+ 0xa61b572d4ad878b8, 0x8b9af023f8602c9f, 0xe7b928217e4811cd, 0x129037e9fd549c7f,+ 0x61ebe7e42502e4be, 0x0a1ee930ea49fb3b, 0x615fc103e28c8e0a, 0x1f73c58f94a72da1,+ 0x5689e070f5399d98, 0xe30fe38ef1ad4366, 0x2a593e06370b77d5, 0x3043c337e1854347,+ 0xe5d72faa615d110c, 0x4038bd291c593240, 0x2ab2bfa552d4b375, 0x8d552f184d7f1bf5,+ 0xf5797da702a9b9e6, 0xe746797066c7d4ae, 0x9ded398ec8b444ad, 0x1677250cc1263ed7,+ 0xcd387dfff99848c8, 0x76c8e17e7e3c51c7, 0x88957499ab90cd0b, 0x61e1f2ed44d22926,+ 0xc67759e92332d47a, 0x20a21f589906abba, 0xcbc97c04dc3600ad, 0xf7c85c33e41fa6a4,+ 0x1097084d6ec2bba1, 0x9fb02d6d6bf6bf94, 0xbe491ed9c83c51e2, 0xa2e98c363d6c67a2,+ 0x9bec27f58f3b5414, 0x194ac1cb82e2d4ab, 0x0064c87914d677a6, 0xcc73278ab09622b6,+ 0x8defa41c9b8b9b51, 0x536cf2c4aa196ece, 0x604a6f8528d890f5, 0x284a26063447d249,+ 0xbe70f37289b5497c, 0x06ddcd30daa6a54f, 0xbfb15004943d67fb, 0x62c1f2bb4bf0265a,+ 0xabe4fe049ba8fd65, 0x20af090e344a0185, 0x416fb2ef6fee28fc, 0xf60d926eacf379b3,+ 0x53610e6411d45e23, 0xf6fb37c66ba64597, 0x42bf7a59192fe853, 0xc04446e8b297e0f2,+ 0x82f1f4d862e3ad59, 0x36ba938e2525ee17, 0x49142470e54f7798, 0x4dfebe5f4e61d2bc,+ 0x15f8c7f7f38338d2, 0x4f36f36937336521, 0xfff70db1621739c8, 0x77768d16df7f7308,+ 0x55e4ad3f457a73b9, 0x89fe259e513d73ef, 0x1e087e74e73661ad, 0x6c8c61983b203db0,+ 0xbe4846ae96db0e56, 0x97fb0e4e2ec84ad6, 0xf6a841d652558edc, 0x6c8c5a1c2b137937,+ 0x9f93197506451b99, 0x3234216f7492d666, 0x0969310ecbc88bc6, 0x1f38f4918779c317,+ 0xfb9d10f0c3a4c23d, 0xb89b140d8f11c5be, 0x10decb1f791bebae, 0x8009d5919e8262f3,+ 0x9f0cedd8d7d130ab, 0xd14db528d87ee2db, 0x4c180eba3157ac53, 0x6c8897a62e2830a2,+ 0x46e03299b3b35cf0, 0xe113872493896b19, 0xf1209451f7a4ff94, 0xb939749bf938eebc,+ 0xb16291a34e66e625, 0x007182e94e603784, 0xb1ae9121fa1a1d1b, 0x6ec222ddf28dca0c,+ 0x28854d8b1e655115, 0x6332ac9c0d1199a2, 0x365fdd7aeebe647e, 0x0fd7033c86765869,+ 0x6c516b8859c8bb01, 0x46c24f980413490f, 0xf867fb37bb76dea9, 0x892d78d1aa3f9fcb,+ 0xcd175fb5a96963ed, 0x5f617cb58fbc8a77, 0x4df29395bddc578d, 0x7d69552224bb6149,+ 0x3584177015ff325b, 0x816acc8a1c352448, 0x449c10951bca892e, 0xadc4d1fcef7ff534,+ 0x64d0275a80e466a4, 0x402f692c29a12441, 0xeec7a5bf7941d5d0, 0x5f166583c2601ed5,+ 0x3b6838dd02fe672f, 0xccedf39242f8c018, 0x07d8c86783c02ffc, 0xaf49620443a23682,+ 0xd91abe9b213695a2, 0x69163f8bf62b1b7c, 0xe31b2e1d8310913f, 0x0c3d7e22dfc2d09c,+ 0x756b39a23e62c096, 0xcc2687b10d550a4c, 0x5b6b449b793b7ae4, 0x1b860384dc8e65e7,+ 0xdf57565c73e4c5f8, 0x5ad5f2b6fc9d0ed3, 0x86b2d2094d589220, 0x1db728b73e4dcef6,+ 0xe2a136a5157f2ca3, 0x08d4b194366445ae, 0xda7f156e2e85d3a9, 0x6c3d56f62df389e9,+ 0xd4874f9387cb7964, 0xa514cb3f14f74eed, 0x1f37e5ff29d299ee, 0xea7429deb1b71032,+ 0x963db43d9b95b0aa, 0x582b6be2902ffc67, 0x2e926ea8a00af35d, 0x92093f9d25126fab,+ 0x344f7c282e4122ec, 0x87ff7054daeb429b, 0xc49f0e4726d146b9, 0xe0773071e66e17e5,+ 0xb345dfdb70eee881, 0x9d8e2b9bedc39423, 0x3ebf8325c8ecd78b, 0x9a226652626286c4,+ 0x96edb25817f1138e, 0xcbb693398017b173, 0x786633d49e99af60, 0xb225db9832e7d8df,+ 0x4cec56b4202c7d7f, 0x18c8278d6ff7825d, 0xed46971bf16adef4, 0x522c06f1fa3978df,+ 0x8d40437999463947, 0xc8959f60eb0d27ad, 0xb9a089058f480f80, 0x215482f345e3c2d5,+ 0xf91c64d2b1b525b9, 0xb68bd03968c728fa, 0x8b12cebebc865819, 0x6d60b167f805c0d4,+ 0x40d773d869517dc2, 0xdb50fd3858eb7ee6, 0x5af4344ac6a899c7, 0xb055dc42b7329b9b,+ 0x2314a1c54ecfe1c7, 0x0eaeed2e3c60c346, 0xfe5614b9ebe6329b, 0x8592445ff13752f9,+]--- /dev/null+++ b/src/src/cli/fsck_cmd.sx@@ -0,0 +1,21 @@+/// `vn fsck`: verify the repository.++val str = use("std/string")+val stdio = use("std/stdio")+val layout = use("../store/layout.sx")+val fsck = use("../store/fsck.sx")++pub fn run(path: str.StringView, verbose: bool) i32 = trust {+ val repo_opt = layout.discover(path)+ val status: mut i32 = 1+ match repo_opt {+ some repo => {+ status = fsck.check(repo, verbose)+ layout.free_repo(repo)+ }+ none => {+ stdio.eprint("vn: not a vein repository: {s}\n", {path})+ }+ }+ return status+}--- /dev/null+++ b/src/src/cli/init_cmd.sx@@ -0,0 +1,20 @@+/// `vn init`: create the on-disk repository skeleton.++val str = use("std/string")+val stdio = use("std/stdio")+val layout = use("../store/layout.sx")++pub fn run(path: str.StringView) i32 = {+ val result = layout.init(path)+ match result {+ ok repo => {+ trust stdio.print("initialized vein repository at {s}\n", {layout.root_view(repo)})+ layout.free_repo(repo)+ return 0+ }+ err code => {+ trust stdio.eprint("vn: init failed with code {d}\n", {code})+ return 1+ }+ }+}--- /dev/null+++ b/src/src/cli/selftest_cmd.sx@@ -0,0 +1,538 @@+/// Internal M0 self-test. This is not part of the formal `vn` interface, but+/// it exercises every codec and the pack/index/op-log round trip without a+/// harness.++val stdio = use("std/stdio")+val str = use("std/string")+val time = use("std/time")+val bytes = use("../core/bytes.sx")+val buf = use("../core/buf.sx")+val reader = use("../core/reader.sx")+val lists = use("../core/lists.sx")+val prim = use("../core/primitives.sx")+val b3 = use("../crypto/blake3.sx")+val fastcdc = use("../chunking/fastcdc.sx")+val blob = use("../object/blob.sx")+val tree = use("../object/tree.sx")+val conflict = use("../object/conflict.sx")+val commit = use("../object/commit.sx")+val operation = use("../object/operation.sx")+val view = use("../object/view.sx")+val objid = use("../object/id.sx")+val types = use("../object/types.sx")+val raw = use("../object/raw.sx")+val layout = use("../store/layout.sx")+val store = use("../store/store.sx")+val pack = use("../store/pack.sx")+val index = use("../store/index.sx")+val fsck = use("../store/fsck.sx")+val files = use("../io/files.sx")++fn fill_pattern(p: ref u8, n: usize, seed: usize) void = trust {+ val i: mut usize = 0+ for i < n {+ val v: u8 = ((i * 31 + seed * 17) % 251) as u8+ @store8(@ptradd(p, i as i64), v)+ i = i + 1+ }+}++fn check_hash(data: ref u8, n: usize, expected_hex: ref u8) bool = trust {+ val out: ref u8 = @alloc(32) as ref u8+ b3.hash(data, n, out)+ val want: ref u8 = @alloc(32) as ref u8+ val parsed: bool = objid.hex_decode(expected_hex, 32, want)+ val same: bool = parsed && bytes.Bytes.eql(bytes.bytes(out, 32), bytes.bytes(want, 32))+ @free(out as ref void)+ @free(want as ref void)+ return same+}++fn assert_id(id: objid.Id, expected_hex: ref u8) void = trust {+ val hx: ref u8 = objid.Id.hex(id)+ val same: bool = bytes.Bytes.eql(bytes.from_cstr(hx), bytes.from_cstr(expected_hex))+ @free(hx as ref void)+ assert same+}++fn assert_bytes_hex(data: bytes.Bytes, expected_hex: ref u8) void = trust {+ val hx: ref u8 = @alloc(data.len * 2 + 1) as ref u8+ objid.hex_encode(data.ptr, data.len, hx)+ @store8(@ptradd(hx, (data.len * 2) as i64), 0)+ val same: bool = bytes.Bytes.eql(bytes.from_cstr(hx), bytes.from_cstr(expected_hex))+ @free(hx as ref void)+ assert same+}++fn assert_bytes_hash(data: bytes.Bytes, expected_hex: ref u8) void = trust {+ val digest: ref u8 = @alloc(32) as ref u8+ b3.hash(data.ptr, data.len, digest)+ assert_bytes_hex(bytes.bytes(digest, 32), expected_hex)+ @free(digest as ref void)+}++fn fuzz_once(data: bytes.Bytes) void = trust {+ val b = blob.decode(data)+ match b {+ ok x => {+ blob.free_blob(x)+ }+ err _ => {+ }+ }+ val t = tree.decode(data)+ match t {+ ok x => {+ tree.free_tree(x)+ }+ err _ => {+ }+ }+ val c = conflict.decode(data)+ match c {+ ok x => {+ conflict.free_conflict(x)+ }+ err _ => {+ }+ }+ val cm = commit.decode(data)+ match cm {+ ok x => {+ commit.free_commit(x)+ }+ err _ => {+ }+ }+ val op = operation.decode(data)+ match op {+ ok x => {+ operation.free_operation(x)+ }+ err _ => {+ }+ }+ val v = view.decode(data)+ match v {+ ok x => {+ view.free_view(x)+ }+ err _ => {+ }+ }+ val p = pack.decode(data)+ match p {+ ok x => {+ pack.free_pack(x)+ }+ err _ => {+ }+ }+ val idx = index.decode(data, bytes.empty())+ match idx {+ ok x => {+ index.free_index(x)+ }+ err _ => {+ }+ }+ val r: mut reader.Reader = reader.new(data.ptr, data.len)+ for {+ val x = reader.Reader.read_varint(r)+ if x is err _ {+ break+ }+ }+ val r2: mut reader.Reader = reader.new(data.ptr, data.len)+ for {+ val x = reader.Reader.read_opt_id(r2)+ if x is err _ {+ break+ }+ }+}++fn test_fuzz() void = trust {+ val capacity: usize = 2048+ val data: ref u8 = @alloc(capacity) as ref u8+ val state: mut u64 = 0x9e3779b97f4a7c15+ val i: mut usize = 0+ for i < 5000 {+ state = state ^ (state << 13)+ state = state ^ (state >> 7)+ state = state ^ (state << 17)+ val n: usize = (state % (capacity as u64)) as usize+ val j: mut usize = 0+ for j < n {+ state = state ^ (state << 13)+ state = state ^ (state >> 7)+ state = state ^ (state << 17)+ @store8(@ptradd(data, j as i64), (state & 255) as u8)+ j = j + 1+ }+ fuzz_once(bytes.bytes(data, n))+ i = i + 1+ }+ @free(data as ref void)+}++fn test_pack_layout() void = trust {+ val body: bytes.Bytes = bytes.Bytes.dup(bytes.bytes(c"\x00", 1))+ val objects: mut list[ref raw.RawObject] = raw.empty_list()+ @append(objects, raw.raw(types.TREE, body))+ val out: pack.PackOutput = pack.encode(objects)+ assert_bytes_hex(out.pack, c"56504b3101000000010000000000000001fd6e74c2454903e76762c71e9f22f7418e5d36f6149c48eeee734ec2e3dc410300010100294c1017488cc29fd32a67b299e998e7d995f5636ef245e1a5bc47be5c1e1042")+ assert_bytes_hash(out.index, c"64bae9db19aa5bf84e4fe72e9cfe38e9563c5baa04abb4a4ca887dbdc94e4b1a")+ val bp: mut ref void = body.ptr as ref void+ @free(bp)+ @listfree(objects)+ pack.free_output(out)+}++fn test_blake3() void = trust {+ assert check_hash(c"", 0, c"af1349b9f5f9a1a6a0404dea36dcc9499bcb25c9adc112b7cc9a93cae41f3262")+ assert check_hash(c"abc", 3, c"6437b3ac38465133ffb63b75273a8db548c558465d79db03fd359c6cd5bd9d85")+ assert check_hash(+ c"hello world",+ 11,+ c"d74981efa70a0c880b8d8c1985d075dbcbf679b99a5f9914e5aaf96b831a9e24"+ )+}++fn test_varint() void = trust {+ val b: mut buf.Buf = buf.new(16)+ buf.Buf.put_varint(b, 0)+ buf.Buf.put_varint(b, 127)+ buf.Buf.put_varint(b, 128)+ buf.Buf.put_varint(b, 300)+ buf.Buf.put_varint(b, 18446744073709551615)+ val r: mut reader.Reader = reader.new(b.ptr, b.len)+ assert (reader.Reader.read_varint(r)?) == 0+ assert (reader.Reader.read_varint(r)?) == 127+ assert (reader.Reader.read_varint(r)?) == 128+ assert (reader.Reader.read_varint(r)?) == 300+ assert (reader.Reader.read_varint(r)?) == 18446744073709551615+ reader.Reader.finish(r)?+ buf.Buf.free(b)+}++fn test_chunker() void = trust {+ val n: usize = 300000+ val data: ref u8 = @alloc(n) as ref u8+ fill_pattern(data, n, 2)+ val lens: list[usize] = fastcdc.split(data, n)+ assert @len(lens) == 2+ match @get(lens, 0) {+ some f => {+ assert f == 262144+ }+ none => {+ assert false+ }+ }+ match @get(lens, 1) {+ some s => {+ assert s == 37856+ }+ none => {+ assert false+ }+ }+ val total: mut usize = 0+ for l in lens {+ assert l >= 1 && l <= fastcdc.MAX_SIZE+ total = total + l+ }+ assert total == n+ val c0 = objid.object_id(types.CHUNK, bytes.Bytes.slice(bytes.bytes(data, n), 0, 262144))+ assert_id(c0, c"a6a4efd6c6330d328e0a3e2a97fb6202771433ffeeea099a93f8df08399b44fd")+ val c1 = objid.object_id(types.CHUNK, bytes.Bytes.slice(bytes.bytes(data, n), 262144, n))+ assert_id(c1, c"4c899670c3ec130e9ce03b5061d2593c2fa4f66661c6285f470e57dc65284444")+ val built: ref blob.BlobBuild = blob.build(data, n)+ val root = objid.object_id(types.BLOB, built.root_body)+ assert_id(root, c"34bb8e7c00665b61c882fe1cae0a51a44d6ad1719fd44a1b22c991ae6a3c24bc")+ assert_id(blob.root_id(built), c"34bb8e7c00665b61c882fe1cae0a51a44d6ad1719fd44a1b22c991ae6a3c24bc")+ val brp: mut ref void = built.root as ref void+ @free(brp)+ blob.free_build(built)+ val p0: mut ref void = c0.ptr as ref void+ val p1: mut ref void = c1.ptr as ref void+ val p2: mut ref void = root.ptr as ref void+ @free(p0)+ @free(p1)+ @free(p2)+ @listfree(lens)+ @free(data as ref void)+}++fn write_one(repo: layout.Repo, kind: u8, body: bytes.Bytes) objid.Id = {+ val objects: mut list[ref raw.RawObject] = raw.empty_list()+ @append(objects, raw.raw(kind, body))+ assert store.write_pack(repo, objects)+ @listfree(objects)+ return objid.object_id(kind, body)+}++fn make_inline_blob(repo: layout.Repo, text: bytes.Bytes) objid.Id = {+ val b: mut buf.Buf = buf.new(text.len + 8)+ buf.Buf.put_u8(b, blob.FORM_INLINE)+ buf.Buf.put_length_prefixed(b, text)+ val body: bytes.Bytes = bytes.Bytes.dup(buf.Buf.view(b))+ buf.Buf.free(b)+ val id: objid.Id = write_one(repo, types.BLOB, body)+ val bp: mut ref void = body.ptr as ref void+ trust @free(bp)+ return id+}++fn make_tree(repo: layout.Repo) objid.Id = {+ val entries: list[ref tree.TreeEntry] = lists.new[ref tree.TreeEntry]()+ val bodyr = tree.encode(entries)+ val body: mut bytes.Bytes = bytes.empty()+ match bodyr {+ ok x => {+ body = x+ }+ err _ => {+ assert false+ }+ }+ val id: objid.Id = write_one(repo, types.TREE, body)+ val bp: mut ref void = body.ptr as ref void+ trust @free(bp)+ @listfree(entries)+ return id+}++fn make_commit(repo: layout.Repo, root: objid.Id) objid.Id = {+ val change: ref u8 = @alloc(16) as ref u8+ val i: mut usize = 0+ for i < 16 {+ trust @store8(@ptradd(change, i as i64), (i + 11) as u8)+ i = i + 1+ }+ val sig: prim.Sig = prim.Sig{+ name: bytes.bytes(c"Alice", 5),+ email: bytes.bytes(c"alice@example.com", 17),+ seconds: 1700000000,+ tz_min: 0+ }+ val parents: list[objid.Id] = lists.new[objid.Id]()+ val renames: list[ref commit.Rename] = lists.new[ref commit.Rename]()+ val extra: list[ref prim.KeyValue] = lists.new[ref prim.KeyValue]()+ val c: mut commit.Commit = commit.Commit{+ version: 1,+ parents: parents,+ root_tree: root,+ change_id: objid.change_id(change),+ author: sig,+ committer: sig,+ message: bytes.bytes(c"initial commit", 14),+ renames_state: commit.RENAMES_RECORDED,+ renames: renames,+ extra: extra+ }+ val body: bytes.Bytes = commit.encode(@addr(c))+ val decoded = commit.decode(body)+ match decoded {+ ok d => {+ assert d.version == 1+ assert @len(d.parents) == 0+ assert objid.ChangeId.eql(d.change_id, objid.change_id(change))+ assert bytes.Bytes.eql(d.message, bytes.bytes(c"initial commit", 14))+ commit.free_commit(d)+ }+ err _ => {+ assert false+ }+ }+ val id: objid.Id = write_one(repo, types.COMMIT, body)+ val bp: mut ref void = body.ptr as ref void+ trust @free(bp)+ trust @free(change as ref void)+ @listfree(parents)+ @listfree(renames)+ @listfree(extra)+ return id+}++fn make_conflict(repo: layout.Repo) objid.Id = {+ val base: objid.Id = make_inline_blob(repo, bytes.bytes(c"base", 4))+ val ours: objid.Id = make_inline_blob(repo, bytes.bytes(c"ours", 4))+ val theirs: objid.Id = make_inline_blob(repo, bytes.bytes(c"theirs", 6))+ val adds: mut list[ref conflict.ConflictValue] = lists.new[ref conflict.ConflictValue]()+ val removes: mut list[ref conflict.ConflictValue] = lists.new[ref conflict.ConflictValue]()+ @append(adds, conflict.value(tree.KIND_FILE, ours))+ @append(adds, conflict.value(tree.KIND_FILE, theirs))+ @append(removes, conflict.value(tree.KIND_FILE, base))+ val body: bytes.Bytes = conflict.encode(adds, removes)+ val decoded = conflict.decode(body)+ match decoded {+ ok d => {+ assert @len(d.adds) == 2+ assert @len(d.removes) == 1+ conflict.free_conflict(d)+ }+ err _ => {+ assert false+ }+ }+ val id: objid.Id = write_one(repo, types.CONFLICT, body)+ val bp: mut ref void = body.ptr as ref void+ trust @free(bp)+ for v in adds {+ val vp: mut ref void = v as ref void+ trust @free(vp)+ }+ for v in removes {+ val vp2: mut ref void = v as ref void+ trust @free(vp2)+ }+ @listfree(adds)+ @listfree(removes)+ return id+}++fn make_view(repo: layout.Repo, head: objid.Id) objid.Id = {+ val heads: mut list[objid.Id] = lists.new[objid.Id]()+ @append(heads, head)+ val bm: mut ref view.Bookmark = @alloc(@sizeof(view.Bookmark)) as ref view.Bookmark+ bm.name = bytes.bytes(c"main", 4)+ val badds: mut list[objid.Id] = lists.new[objid.Id]()+ @append(badds, head)+ val brems: list[objid.Id] = lists.new[objid.Id]()+ bm.targets = view.TargetSet{adds: badds, removes: brems}+ val bookmarks: mut list[ref view.Bookmark] = lists.new[ref view.Bookmark]()+ @append(bookmarks, bm)+ val tags: list[ref view.TagRef] = lists.new[ref view.TagRef]()+ val remotes: list[ref view.RemoteRef] = lists.new[ref view.RemoteRef]()+ val wc: mut ref view.WorkspaceRef = @alloc(@sizeof(view.WorkspaceRef)) as ref view.WorkspaceRef+ wc.workspace = bytes.bytes(c"default", 7)+ wc.target = head+ val wcs: mut list[ref view.WorkspaceRef] = lists.new[ref view.WorkspaceRef]()+ @append(wcs, wc)+ val v: mut view.View = view.View{+ heads: heads,+ bookmarks: bookmarks,+ tags: tags,+ remote_refs: remotes,+ working_copies: wcs+ }+ val body: bytes.Bytes = view.encode(@addr(v))+ val decoded = view.decode(body)+ match decoded {+ ok d => {+ assert @len(d.heads) == 1+ assert @len(d.bookmarks) == 1+ assert @len(d.working_copies) == 1+ view.free_view(d)+ }+ err _ => {+ assert false+ }+ }+ val id: objid.Id = write_one(repo, types.VIEW, body)+ val bp: mut ref void = body.ptr as ref void+ trust @free(bp)+ @listfree(heads)+ @listfree(badds)+ @listfree(brems)+ @listfree(bookmarks)+ @listfree(tags)+ @listfree(remotes)+ @listfree(wcs)+ trust @free(bm as ref void)+ trust @free(wc as ref void)+ return id+}++fn make_operation(repo: layout.Repo, view_id: objid.Id) objid.Id = {+ val parents: list[objid.Id] = lists.new[objid.Id]()+ val tags: list[ref prim.KeyValue] = lists.new[ref prim.KeyValue]()+ val tm: prim.TimeMs = prim.TimeMs{ms: 1700000000000, tz_min: 0}+ val op: mut operation.Operation = operation.Operation{+ parents: parents,+ view: view_id,+ start: tm,+ end: tm,+ hostname: bytes.bytes(c"host", 4),+ username: bytes.bytes(c"alice", 5),+ description: bytes.bytes(c"selftest operation", 18),+ tags: tags+ }+ val body: bytes.Bytes = operation.encode(@addr(op))+ val decoded = operation.decode(body)+ match decoded {+ ok d => {+ assert objid.Id.eql(d.view, view_id)+ assert bytes.Bytes.eql(d.description, bytes.bytes(c"selftest operation", 18))+ operation.free_operation(d)+ }+ err _ => {+ assert false+ }+ }+ val id: objid.Id = write_one(repo, types.OPERATION, body)+ val bp: mut ref void = body.ptr as ref void+ trust @free(bp)+ @listfree(parents)+ @listfree(tags)+ return id+}++fn mark_op_head(repo: layout.Repo, id: objid.Id) void = {+ val hx: ref u8 = objid.Id.hex(id)+ val dir: str.StringView = layout.op_heads_dir(repo)+ val p: str.StringView = files.join(dir, str.from_cstr(hx))+ assert files.write_all(p, bytes.empty())+ files.free_path(p)+ files.free_path(dir)+ trust @free(hx as ref void)+}++fn test_repository(repo: layout.Repo) void = trust {+ val tree_id: objid.Id = make_tree(repo)+ assert_id(tree_id, c"01fd6e74c2454903e76762c71e9f22f7418e5d36f6149c48eeee734ec2e3dc41")+ val commit_id: objid.Id = make_commit(repo, tree_id)+ assert_id(commit_id, c"c6a60eba55e527a7b746aee77e66fc5e8e60ef31c5c407d57eaceaeececebb3c")+ val conflict_id: objid.Id = make_conflict(repo)+ assert_id(conflict_id, c"d6d530d1e90142531d26d6db8489b0c42654b312d27b56f74b45d97f2b00e7a9")+ val view_id: objid.Id = make_view(repo, commit_id)+ assert_id(view_id, c"9ba517b0693bd2016b9662f18fb54ca0ceaadc2ab08c4d87d9c4c9e42e689eed")+ val op_id: objid.Id = make_operation(repo, view_id)+ assert_id(op_id, c"99a9dea611815d7320e8481495227bf62e8a224ec873f3cd1daca5b4e2ece4f1")+ mark_op_head(repo, op_id)+ assert !objid.Id.is_none(conflict_id)+}++pub fn run() i32 = trust {+ test_blake3()+ test_varint()+ test_pack_layout()+ test_chunker()+ test_fuzz()++ val path: ref u8 = @fmtalloc("/tmp/opencode/vein-selftest-{d}", {time.unix_now_micros()})+ val repo_r = layout.init(str.from_cstr(path))+ val repo: mut layout.Repo = layout.Repo{root: bytes.empty()}+ match repo_r {+ ok r => {+ repo = r+ }+ err e => {+ stdio.eprint("selftest: cannot create repo ({d})\n", {e})+ @free(path as ref void)+ return 1+ }+ }+ test_repository(repo)+ val status: i32 = fsck.check(repo, false)+ layout.free_repo(repo)+ @free(path as ref void)+ if status != 0 {+ stdio.eprint("selftest: fsck failed\n", {})+ return 1+ }+ stdio.puts("selftest: OK")+ return 0+}--- /dev/null+++ b/src/src/core/buf.sx@@ -0,0 +1,164 @@+/// A growable byte buffer used to build canonical encodings.+///+/// Trust in this module is confined to the raw memory operations. The public+/// API is safe to call from ordinary code.++val bytes = use("bytes.sx")+val prim = use("primitives.sx")++val INITIAL_CAPACITY: usize = 64++pub type Buf = {+ ptr: mut ref u8+ len: mut usize+ cap: mut usize+}++pub fn new(capacity: usize) Buf = {+ val cap: mut usize = capacity+ if cap < INITIAL_CAPACITY {+ cap = INITIAL_CAPACITY+ }+ val p: ref u8 = @alloc(cap) as ref u8+ assert p != none+ return Buf{ptr: p, len: 0, cap: cap}+}++pub fn (Buf) free(b: mut self) void = {+ if b.ptr != none {+ trust {+ @free(b.ptr as ref void)+ }+ }+ b.ptr = none+ b.len = 0+ b.cap = 0+}++pub fn (Buf) view(b: self) bytes.Bytes = {+ return bytes.bytes(b.ptr, b.len)+}++pub fn (Buf) reset(b: mut self) void = {+ b.len = 0+}++pub fn (Buf) reserve(b: mut self, extra: usize) void = {+ val need: usize = b.len + extra+ if need <= b.cap {+ return+ }+ val cap: mut usize = b.cap+ for cap < need {+ cap = cap * 2+ }+ trust {+ val p: ref void = @realloc(b.ptr as ref void, cap)+ assert p != none+ b.ptr = p as ref u8+ b.cap = cap+ }+}++pub fn (Buf) put_u8(b: mut self, v: u8) void = {+ Buf.reserve(b, 1)+ trust {+ @store8(@ptradd(b.ptr, b.len as i64), v)+ }+ b.len = b.len + 1+}++pub fn (Buf) put_u16_le(b: mut self, v: u16) void = {+ Buf.put_u8(b, (v & 255) as u8)+ Buf.put_u8(b, ((v >> 8) & 255) as u8)+}++pub fn (Buf) put_u32_le(b: mut self, v: u32) void = {+ Buf.reserve(b, 4)+ trust {+ @store32(@ptradd(b.ptr, b.len as i64), v as i32)+ }+ b.len = b.len + 4+}++pub fn (Buf) put_u64_le(b: mut self, v: u64) void = {+ Buf.reserve(b, 8)+ trust {+ @store64(@ptradd(b.ptr, b.len as i64), v)+ }+ b.len = b.len + 8+}++pub fn (Buf) put_i16_le(b: mut self, v: i16) void = {+ Buf.put_u16_le(b, v as u16)+}++pub fn (Buf) put_i64_le(b: mut self, v: i64) void = {+ Buf.put_u64_le(b, v as u64)+}++pub fn (Buf) put_raw(b: mut self, p: ref u8, n: usize) void = {+ if n == 0 {+ return+ }+ Buf.reserve(b, n)+ trust {+ @memcpy(@ptradd(b.ptr, b.len as i64), p as ref void, n)+ }+ b.len = b.len + n+}++pub fn (Buf) put_bytes(b: mut self, v: bytes.Bytes) void = {+ Buf.put_raw(b, v.ptr, v.len)+}++pub fn (Buf) put_varint(b: mut self, value: u64) void = {+ val v: mut u64 = value+ for {+ val low: u8 = (v & 127) as u8+ v = v >> 7+ if v == 0 {+ Buf.put_u8(b, low)+ break+ }+ Buf.put_u8(b, low | 128)+ }+}++pub fn (Buf) put_length_prefixed(b: mut self, v: bytes.Bytes) void = {+ Buf.put_varint(b, v.len as u64)+ Buf.put_bytes(b, v)+}++pub fn (Buf) put_opt_id(b: mut self, p: ref u8) void = {+ if p == none {+ Buf.put_u8(b, 0)+ return+ }+ Buf.put_u8(b, 1)+ Buf.put_raw(b, p, 32)+}++pub fn (Buf) put_id(b: mut self, p: ref u8) void = {+ pre {+ present: p != none+ }+ Buf.put_raw(b, p, 32)+}++pub fn (Buf) put_sig(b: mut self, v: prim.Sig) void = {+ Buf.put_length_prefixed(b, v.name)+ Buf.put_length_prefixed(b, v.email)+ Buf.put_i64_le(b, v.seconds)+ Buf.put_i16_le(b, v.tz_min)+}++pub fn (Buf) put_time_ms(b: mut self, v: prim.TimeMs) void = {+ Buf.put_i64_le(b, v.ms)+ Buf.put_i16_le(b, v.tz_min)+}++pub fn (Buf) put_kv(b: mut self, v: prim.KeyValue) void = {+ Buf.put_length_prefixed(b, v.key)+ Buf.put_length_prefixed(b, v.value)+}--- /dev/null+++ b/src/src/core/bytes.sx@@ -0,0 +1,140 @@+/// Borrowed byte spans used throughout the object codecs.+///+/// A `Bytes` value never owns its storage. Decoders return views into the+/// object body they were given; encoders return views into a `Buf` that the+/// caller still owns.++pub type Bytes = {+ ptr: ref u8+ len: usize+}+pub fn bytes(ptr: ref u8, len: usize) Bytes = {+ if ptr == none {+ return Bytes{ptr: none, len: 0}+ }+ return Bytes{ptr: ptr, len: len}+}++pub fn empty() Bytes = {+ return Bytes{ptr: none, len: 0}+}++pub fn (Bytes) is_empty(b: self) bool = {+ return b.len == 0+}++pub fn (Bytes) at(b: self, i: usize) u8 = {+ pre {+ in_bounds: i < b.len+ }+ return trust @load8(@ptradd(b.ptr, i as i64))+}++pub fn (Bytes) slice(b: self, start: usize, end: usize) Bytes = {+ pre {+ ordered: start <= end+ in_bounds: end <= b.len+ }+ if start == end {+ return empty()+ }+ val out: Bytes = Bytes{ptr: trust @ptradd(b.ptr, start as i64), len: end - start}+ return out+}++/// Lexicographic comparison over unsigned bytes.+pub fn (Bytes) cmp(a: self, b: Bytes) i64 = {+ val n: mut usize = b.len+ if a.len < b.len {+ n = a.len+ }+ val i: mut usize = 0+ for i < n {+ val ca: u8 = trust @load8(@ptradd(a.ptr, i as i64))+ val cb: u8 = trust @load8(@ptradd(b.ptr, i as i64))+ if ca < cb {+ return -1+ }+ if ca > cb {+ return 1+ }+ i = i + 1+ }+ if a.len < b.len {+ return -1+ }+ if a.len > b.len {+ return 1+ }+ return 0+}++pub fn (Bytes) eql(a: self, b: Bytes) bool = {+ return Bytes.cmp(a, b) == 0+}++/// Case-insensitive comparison restricted to ASCII A-Z.+pub fn (Bytes) eql_ascii_ci(a: self, b: Bytes) bool = {+ if a.len != b.len {+ return false+ }+ val i: mut usize = 0+ for i < a.len {+ val ca: u8 = ascii_lower(trust @load8(@ptradd(a.ptr, i as i64)))+ val cb: u8 = ascii_lower(trust @load8(@ptradd(b.ptr, i as i64)))+ if ca != cb {+ return false+ }+ i = i + 1+ }+ return true+}++fn ascii_lower(c: u8) u8 = {+ if c >= 65 && c <= 90 {+ return (c + 32) as u8+ }+ return c+}++/// Copy `b` into a newly allocated NUL-terminated buffer.+pub fn (Bytes) to_cstr(b: self) ref u8 = {+ val out: ref u8 = @alloc(b.len + 1) as ref u8+ if b.len > 0 {+ trust @memcpy(out as ref void, b.ptr as ref void, b.len)+ }+ trust @store8(@ptradd(out, b.len as i64), 0)+ return out+}++/// Allocate a private copy of a byte span. The caller owns the result.+pub fn (Bytes) dup(b: self) Bytes = {+ if b.len == 0 {+ return empty()+ }+ val out: ref u8 = @alloc(b.len) as ref u8+ trust @memcpy(out as ref void, b.ptr as ref void, b.len)+ return Bytes{ptr: out, len: b.len}+}++pub fn from_cstr(s: ref u8) Bytes = {+ if s == none {+ return empty()+ }+ val n: usize = @strlen(s) as usize+ return Bytes{ptr: s, len: n}+}++pub fn (Bytes) starts_with(b: self, prefix: Bytes) bool = {+ if prefix.len > b.len {+ return false+ }+ val i: mut usize = 0+ for i < prefix.len {+ if trust @load8(@ptradd(b.ptr, i as i64)) != trust @load8(@ptradd(prefix.ptr, i as i64)) {+ return false+ }+ i = i + 1+ }+ return true+}--- /dev/null+++ b/src/src/core/error.sx@@ -0,0 +1,83 @@+/// Decode and storage error kinds shared by the M0 codecs and store.+///+/// Errors carry a byte offset into the object body when one is known. The+/// offset is zero for errors that are not tied to a particular position.++val str = use("std/string")++pub enum ErrorKind = {+ UnexpectedEnd+ NonMinimalVarint+ VarintOverflow+ InvalidValue+ Unsorted+ Duplicate+ LimitExceeded+ InvalidName+ InvalidMagic+ UnsupportedVersion+ TrailingBytes+ HashMismatch+ NotFound+ Io+ Corrupt+}+pub type DecodeError = {+ kind: ErrorKind+ offset: usize+}+pub fn fail(kind: ErrorKind, offset: usize) DecodeError = {+ return DecodeError{kind: kind, offset: offset}+}++/// Short, stable text for diagnostics.+pub fn (ErrorKind) name(k: self) str.StringView = {+ match k {+ ErrorKind.UnexpectedEnd => {+ return "unexpected end of input"+ }+ ErrorKind.NonMinimalVarint => {+ return "non-minimal varint"+ }+ ErrorKind.VarintOverflow => {+ return "varint overflow"+ }+ ErrorKind.InvalidValue => {+ return "invalid value"+ }+ ErrorKind.Unsorted => {+ return "entries are not sorted"+ }+ ErrorKind.Duplicate => {+ return "duplicate entry"+ }+ ErrorKind.LimitExceeded => {+ return "format limit exceeded"+ }+ ErrorKind.InvalidName => {+ return "invalid name"+ }+ ErrorKind.InvalidMagic => {+ return "bad file magic"+ }+ ErrorKind.UnsupportedVersion => {+ return "unsupported format version"+ }+ ErrorKind.TrailingBytes => {+ return "trailing bytes"+ }+ ErrorKind.HashMismatch => {+ return "hash mismatch"+ }+ ErrorKind.NotFound => {+ return "object not found"+ }+ ErrorKind.Io => {+ return "I/O error"+ }+ ErrorKind.Corrupt => {+ return "corrupt data"+ }+ }+ return "unknown error"+}--- /dev/null+++ b/src/src/core/lists.sx@@ -0,0 +1,20 @@+/// Allocation helpers for the core list representation.++val allocators = use("std/allocators")++/// Create an empty heap-backed list. Allocation failure is fatal, because the+/// M0 tools have no meaningful way to continue without memory.+pub fn new[T]() list[T] = {+ val heap: allocators.HeapAllocator = @zeroed+ val r = @listalloc[allocators.HeapAllocator, T](heap)+ match r {+ ok l => {+ return l+ }+ err _ => {+ assert false+ val empty: list[T] = @zeroed+ return empty+ }+ }+}--- /dev/null+++ b/src/src/core/primitives.sx@@ -0,0 +1,28 @@+/// Small canonical value types shared by object encoders and decoders.++val bytes = use("bytes.sx")++/// A name/email/message/path span. Borrowed from the caller's buffer.+pub type Sig = {+ name: bytes.Bytes+ email: bytes.Bytes+ seconds: i64+ tz_min: i16+}+pub type TimeMs = {+ ms: i64+ tz_min: i16+}+pub type KeyValue = {+ key: bytes.Bytes+ value: bytes.Bytes+}+pub val MAX_NAME_LEN: usize = 4096+pub val MAX_PATH_LEN: usize = 65536+pub val MAX_MESSAGE_LEN: usize = 16777216+pub val MAX_OBJECT_BODY: usize = 67108864+pub val MAX_CHUNK_LEN: usize = 262144+pub val MAX_MANIFEST_ENTRIES: usize = 1024+pub val MAX_TREE_ENTRIES: usize = 1000000+pub val MAX_CONFLICT_TERMS: usize = 64+pub val INLINE_THRESHOLD: usize = 16384--- /dev/null+++ b/src/src/core/reader.sx@@ -0,0 +1,185 @@+/// A bounded cursor over an object body.+///+/// Trust is confined to raw loads. Public methods are safe and every decoder+/// must call `finish` so that trailing bytes are rejected.++val bytes = use("bytes.sx")+val derr = use("error.sx")+val prim = use("primitives.sx")++pub val MAX_VARINT_BYTES: usize = 10++pub type Reader = {+ data: ref u8+ len: usize+ pos: mut usize+}++pub fn new(data: ref u8, len: usize) Reader = {+ return Reader{data: data, len: len, pos: 0}+}++pub fn (Reader) offset(r: self) usize = {+ return r.pos+}++pub fn (Reader) remaining(r: self) usize = {+ pre {+ consistent: r.pos <= r.len+ }+ return r.len - r.pos+}++pub fn (Reader) at_end(r: self) bool = {+ return r.pos >= r.len+}++pub fn (Reader) fail(r: self, kind: derr.ErrorKind) derr.DecodeError = {+ return derr.fail(kind, r.pos)+}++pub fn (Reader) read_u8(r: mut self) result[u8, derr.DecodeError] = {+ if r.pos >= r.len {+ return err derr.fail(derr.ErrorKind.UnexpectedEnd, r.pos)+ }+ val v: u8 = trust @load8(@ptradd(r.data, r.pos as i64))+ r.pos = r.pos + 1+ return ok v+}++pub fn (Reader) read_u16_le(r: mut self) result[u16, derr.DecodeError] = {+ if Reader.remaining(r) < 2 {+ return err derr.fail(derr.ErrorKind.UnexpectedEnd, r.pos)+ }+ val v: u16 = trust @load16(@ptradd(r.data, r.pos as i64))+ r.pos = r.pos + 2+ return ok v+}++pub fn (Reader) read_u32_le(r: mut self) result[u32, derr.DecodeError] = {+ if Reader.remaining(r) < 4 {+ return err derr.fail(derr.ErrorKind.UnexpectedEnd, r.pos)+ }+ val v: u32 = trust (@load32(@ptradd(r.data, r.pos as i64)) as u32)+ r.pos = r.pos + 4+ return ok v+}++pub fn (Reader) read_u64_le(r: mut self) result[u64, derr.DecodeError] = {+ if Reader.remaining(r) < 8 {+ return err derr.fail(derr.ErrorKind.UnexpectedEnd, r.pos)+ }+ val v: u64 = trust (@load64(@ptradd(r.data, r.pos as i64)) as u64)+ r.pos = r.pos + 8+ return ok v+}++pub fn (Reader) read_i16_le(r: mut self) result[i16, derr.DecodeError] = {+ val v: u16 = Reader.read_u16_le(r)?+ return ok v as i16+}++pub fn (Reader) read_i64_le(r: mut self) result[i64, derr.DecodeError] = {+ val v: u64 = Reader.read_u64_le(r)?+ return ok v as i64+}++pub fn (Reader) read_varint(r: mut self) result[u64, derr.DecodeError] = {+ val start: usize = r.pos+ val value: mut u64 = 0+ val shift: mut u64 = 0+ val i: mut usize = 0+ for i < MAX_VARINT_BYTES {+ val b: u8 = Reader.read_u8(r)?+ val low: u64 = (b & 127) as u64+ if shift == 63 && low > 1 {+ return err derr.fail(derr.ErrorKind.VarintOverflow, start)+ }+ value = value | (low << shift)+ if (b & 128) == 0 {+ if i > 0 && low == 0 {+ return err derr.fail(derr.ErrorKind.NonMinimalVarint, start)+ }+ return ok value+ }+ shift = shift + 7+ i = i + 1+ }+ return err derr.fail(derr.ErrorKind.VarintOverflow, start)+}++pub fn (Reader) read_raw(r: mut self, n: usize) result[bytes.Bytes, derr.DecodeError] = {+ if n > Reader.remaining(r) {+ return err derr.fail(derr.ErrorKind.UnexpectedEnd, r.pos)+ }+ val start: usize = r.pos+ r.pos = r.pos + n+ return ok bytes.bytes(trust @ptradd(r.data, start as i64), n)+}++pub fn (Reader) read_bytes(r: mut self, max_len: usize) result[bytes.Bytes, derr.DecodeError] = {+ val at: usize = r.pos+ val n: u64 = Reader.read_varint(r)?+ if n > max_len as u64 {+ return err derr.fail(derr.ErrorKind.LimitExceeded, at)+ }+ if n > Reader.remaining(r) as u64 {+ return err derr.fail(derr.ErrorKind.UnexpectedEnd, at)+ }+ return Reader.read_raw(r, n as usize)+}++pub fn (Reader) read_list_len(+ r: mut self,+ max: usize+) result[usize, derr.DecodeError] = {+ val at: usize = r.pos+ val n: u64 = Reader.read_varint(r)?+ if n > max as u64 {+ return err derr.fail(derr.ErrorKind.LimitExceeded, at)+ }+ return ok n as usize+}++pub fn (Reader) read_id(r: mut self) result[ref u8, derr.DecodeError] = {+ if Reader.remaining(r) < 32 {+ return err derr.fail(derr.ErrorKind.UnexpectedEnd, r.pos)+ }+ val start: usize = r.pos+ r.pos = r.pos + 32+ return ok trust @ptradd(r.data, start as i64)+}++pub fn (Reader) read_opt_id(r: mut self) result[ref u8, derr.DecodeError] = {+ val tag: u8 = Reader.read_u8(r)?+ if tag == 0 {+ return ok none+ }+ if tag != 1 {+ return err derr.fail(derr.ErrorKind.InvalidValue, r.pos - 1)+ }+ return Reader.read_id(r)+}++pub fn (Reader) read_sig(r: mut self, max_name: usize, max_email: usize) result[prim.Sig, derr.DecodeError] = {+ r.pos = r.pos+ val name: bytes.Bytes = Reader.read_bytes(r, max_name)?+ val email: bytes.Bytes = Reader.read_bytes(r, max_email)?+ val seconds: i64 = Reader.read_i64_le(r)?+ val tz_min: i16 = Reader.read_i16_le(r)?+ return ok prim.Sig{name: name, email: email, seconds: seconds, tz_min: tz_min}+}++pub fn (Reader) read_time_ms(r: mut self) result[prim.TimeMs, derr.DecodeError] = {+ r.pos = r.pos+ val ms: i64 = Reader.read_i64_le(r)?+ val tz_min: i16 = Reader.read_i16_le(r)?+ return ok prim.TimeMs{ms: ms, tz_min: tz_min}+}++pub fn (Reader) finish(r: self) result[void, derr.DecodeError] = {+ if r.pos != r.len {+ return err derr.fail(derr.ErrorKind.TrailingBytes, r.pos)+ }+ return ok()+}--- /dev/null+++ b/src/src/crypto/blake3.sx@@ -0,0 +1,341 @@+/// BLAKE3 (256-bit output), unkeyed mode.+///+/// The implementation is a direct transcription of the BLAKE3 reference+/// algorithm: 1 KiB chunks, a binary Merkle tree, and the standard+/// compression function with the BLAKE3 message schedule. It is deliberately+/// free of platform dependencies so that object IDs are identical everywhere.++val IV: [8]u32 = [+ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,+ 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19+]++val MSG: [112]u32 = [+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,+ 2, 6, 3, 10, 7, 0, 4, 13, 1, 11, 12, 5, 9, 14, 15, 8,+ 3, 4, 10, 12, 13, 2, 7, 14, 6, 5, 9, 0, 11, 15, 8, 1,+ 10, 7, 12, 9, 14, 3, 13, 15, 4, 0, 11, 2, 5, 8, 1, 6,+ 12, 13, 9, 11, 15, 10, 14, 8, 7, 2, 5, 3, 0, 1, 6, 4,+ 9, 14, 11, 5, 8, 12, 15, 1, 13, 3, 0, 10, 2, 6, 4, 7,+ 11, 15, 5, 0, 1, 9, 8, 6, 14, 10, 2, 12, 3, 4, 7, 13+]++pub val CHUNK_START: u64 = 1+pub val CHUNK_END: u64 = 2+pub val PARENT: u64 = 4+pub val ROOT: u64 = 8++val MAX_STACK_DEPTH: usize = 54++fn mask32(x: u64) u64 = {+ return x & 0xffffffff+}++fn rotr(x: u64, n: u64) u64 = {+ val v: u64 = mask32(x)+ return mask32((v >> n) | (v << (32 - n)))+}++fn ldw(p: ref u64, i: usize) u64 = trust {+ return @load64(@ptradd(p, (i * 8) as i64)) as u64+}++fn stw(p: ref u64, i: usize, v: u64) void = trust {+ @store64(@ptradd(p, (i * 8) as i64), v)+}++fn msg_word(r: usize, i: usize) u64 = {+ val o = @get(MSG, r * 16 + i)+ if o is some v {+ return v as u64+ }+ return 0+}++fn iv_word(i: usize) u64 = {+ val o = @get(IV, i)+ if o is some v {+ return v as u64+ }+ return 0+}++fn block_word(block: ref u64, i: u64) u64 = trust {+ val p: ref void = @ptradd(block as ref void, (i * 4) as i64)+ return (@load32(p) as u32) as u64+}++fn g(s: ref u64, a: usize, b: usize, c: usize, d: usize, mx: u64, my: u64) void = trust {+ val x0: mut u64 = mask32(ldw(s, a) + ldw(s, b) + mx)+ val x3: mut u64 = rotr(ldw(s, d) ^ x0, 16)+ val x2: mut u64 = mask32(ldw(s, c) + x3)+ val x1: mut u64 = rotr(ldw(s, b) ^ x2, 12)+ x0 = mask32(x0 + x1 + my)+ x3 = rotr(x3 ^ x0, 8)+ x2 = mask32(x2 + x3)+ x1 = rotr(x1 ^ x2, 7)+ stw(s, a, x0)+ stw(s, b, x1)+ stw(s, c, x2)+ stw(s, d, x3)+}++fn compress_into(+ cv: ref u64,+ block: ref u64,+ counter: u64,+ block_len: u64,+ flags: u64,+ out: ref u64+) void = trust {+ stw(out, 0, ldw(cv, 0))+ stw(out, 1, ldw(cv, 1))+ stw(out, 2, ldw(cv, 2))+ stw(out, 3, ldw(cv, 3))+ stw(out, 4, ldw(cv, 4))+ stw(out, 5, ldw(cv, 5))+ stw(out, 6, ldw(cv, 6))+ stw(out, 7, ldw(cv, 7))+ stw(out, 8, iv_word(0))+ stw(out, 9, iv_word(1))+ stw(out, 10, iv_word(2))+ stw(out, 11, iv_word(3))+ stw(out, 12, mask32(counter))+ stw(out, 13, mask32(counter >> 32))+ stw(out, 14, block_len)+ stw(out, 15, flags)++ val r: mut usize = 0+ for r < 7 {+ g(out, 0, 4, 8, 12, block_word(block, msg_word(r, 0)), block_word(block, msg_word(r, 1)))+ g(out, 1, 5, 9, 13, block_word(block, msg_word(r, 2)), block_word(block, msg_word(r, 3)))+ g(out, 2, 6, 10, 14, block_word(block, msg_word(r, 4)), block_word(block, msg_word(r, 5)))+ g(out, 3, 7, 11, 15, block_word(block, msg_word(r, 6)), block_word(block, msg_word(r, 7)))+ g(out, 0, 5, 10, 15, block_word(block, msg_word(r, 8)), block_word(block, msg_word(r, 9)))+ g(out, 1, 6, 11, 12, block_word(block, msg_word(r, 10)), block_word(block, msg_word(r, 11)))+ g(out, 2, 7, 8, 13, block_word(block, msg_word(r, 12)), block_word(block, msg_word(r, 13)))+ g(out, 3, 4, 9, 14, block_word(block, msg_word(r, 14)), block_word(block, msg_word(r, 15)))+ r = r + 1+ }++ val i: mut usize = 0+ for i < 8 {+ val lo: u64 = ldw(out, i)+ val hi: u64 = ldw(out, i + 8)+ stw(out, i, mask32(lo ^ hi))+ stw(out, i + 8, mask32(hi ^ ldw(cv, i)))+ i = i + 1+ }+}++fn copy_words(dst: ref u64, src: ref u64, n: usize) void = trust {+ val i: mut usize = 0+ for i < n {+ stw(dst, i, ldw(src, i))+ i = i + 1+ }+}++fn set_iv(out_cv: ref u64) void = trust {+ stw(out_cv, 0, iv_word(0))+ stw(out_cv, 1, iv_word(1))+ stw(out_cv, 2, iv_word(2))+ stw(out_cv, 3, iv_word(3))+ stw(out_cv, 4, iv_word(4))+ stw(out_cv, 5, iv_word(5))+ stw(out_cv, 6, iv_word(6))+ stw(out_cv, 7, iv_word(7))+}++fn output_cv(+ cv: ref u64,+ block: ref u64,+ counter: u64,+ block_len: u64,+ flags: u64,+ scratch: ref u64,+ out_cv: ref u64+) void = trust {+ compress_into(cv, block, counter, block_len, flags, scratch)+ copy_words(out_cv, scratch, 8)+}++/// Compute the (pre-final-block) chaining value, final block, and flags of a+/// chunk. `out_block` receives the 16 little-endian message words.+fn chunk_finalize(+ data: ref u8,+ len: usize,+ counter: u64,+ out_cv: ref u64,+ out_block: ref u64,+ out_flags: ref u64,+ out_counter: ref u64,+ out_block_len: ref u64+) void = trust {+ set_iv(out_cv)+ val total: usize = (len + 63) / 64+ val blk: ref u64 = @alloc(64) as ref u64+ val state: ref u64 = @alloc(128) as ref u64++ val i: mut usize = 0+ for i + 1 < total {+ @memset(blk, 0, 64)+ val blk_ptr: ref u8 = @ptradd(data, (i * 64) as i64)+ @memcpy(blk as ref void, blk_ptr as ref void, 64)+ val cf: mut u64 = 0+ if i == 0 {+ cf = CHUNK_START+ }+ compress_into(out_cv, blk, counter, 64, cf, state)+ copy_words(out_cv, state, 8)+ i = i + 1+ }++ @memset(out_block, 0, 64)+ val last_len: usize = len - (i * 64)+ if last_len > 0 {+ val blk_ptr2: ref u8 = @ptradd(data, (i * 64) as i64)+ @memcpy(out_block as ref void, blk_ptr2 as ref void, last_len)+ }+ val start_flag: mut u64 = 0+ if i == 0 {+ start_flag = CHUNK_START+ }+ @store64(out_flags, start_flag | CHUNK_END)+ @store64(out_counter, counter)+ @store64(out_block_len, last_len as u64)++ @free(blk as ref void)+ @free(state as ref void)+}++/// Pack two 32-byte chaining values into a parent block.+fn parent_output(left: ref u64, right: ref u64, out_cv: ref u64, out_block: ref u64) void = trust {+ set_iv(out_cv)+ val i: mut usize = 0+ for i < 8 {+ @store32(@ptradd(out_block as ref void, (i * 4) as i64), ldw(left, i) as i32)+ @store32(@ptradd(out_block as ref void, ((i + 8) * 4) as i64), ldw(right, i) as i32)+ i = i + 1+ }+}++fn push_cv(stack: ref u64, depth: usize, cv: ref u64) void = trust {+ val base: ref u64 = @ptradd(stack, (depth * 64) as i64) as ref u64+ copy_words(base, cv, 8)+}++fn pop_cv(stack: ref u64, depth: usize, out: ref u64) void = trust {+ val base: ref u64 = @ptradd(stack, (depth * 64) as i64) as ref u64+ copy_words(out, base, 8)+}++/// Hash `len` bytes at `data` and write the 32-byte digest to `out`.+pub fn hash(data: ref u8, len: usize, out: ref u8) void = trust {+ val stack: ref u64 = @alloc((MAX_STACK_DEPTH + 1) * 64) as ref u64+ val scratch: ref u64 = @alloc(128) as ref u64+ val out_cv: ref u64 = @alloc(64) as ref u64+ val out_block: ref u64 = @alloc(64) as ref u64+ val out_flags: ref u64 = @alloc(8) as ref u64+ val out_counter: ref u64 = @alloc(8) as ref u64+ val out_block_len: ref u64 = @alloc(8) as ref u64+ val chunk_cv: ref u64 = @alloc(64) as ref u64+ val new_cv: ref u64 = @alloc(64) as ref u64+ val left: ref u64 = @alloc(64) as ref u64+ val cur_cv: ref u64 = @alloc(64) as ref u64++ val total_chunks: mut u64 = ((len + 1023) / 1024) as u64+ if len == 0 {+ total_chunks = 1+ }+ val depth: mut usize = 0+ val i: mut u64 = 0+ for i + 1 < total_chunks {+ val off: usize = (i as usize) * 1024+ chunk_finalize(+ @ptradd(data, off as i64),+ 1024,+ i,+ out_cv,+ out_block,+ out_flags,+ out_counter,+ out_block_len+ )+ output_cv(out_cv, out_block, i, 64, @load64(out_flags), scratch, chunk_cv)+ copy_words(new_cv, chunk_cv, 8)+ val total_so_far: mut u64 = i + 1+ for mask32(total_so_far & 1) == 0 {+ pop_cv(stack, depth - 1, left)+ depth = depth - 1+ parent_output(left, new_cv, out_cv, out_block)+ @store64(out_flags, PARENT)+ @store64(out_counter, 0)+ @store64(out_block_len, 64)+ output_cv(out_cv, out_block, 0, 64, PARENT, scratch, new_cv)+ total_so_far = total_so_far >> 1+ }+ push_cv(stack, depth, new_cv)+ depth = depth + 1+ i = i + 1+ }++ val last_off: usize = (i as usize) * 1024+ val last_len: usize = len - last_off+ chunk_finalize(+ @ptradd(data, last_off as i64),+ last_len,+ i,+ out_cv,+ out_block,+ out_flags,+ out_counter,+ out_block_len+ )++ for depth > 0 {+ pop_cv(stack, depth - 1, left)+ depth = depth - 1+ output_cv(+ out_cv,+ out_block,+ @load64(out_counter),+ @load64(out_block_len),+ @load64(out_flags),+ scratch,+ cur_cv+ )+ parent_output(left, cur_cv, out_cv, out_block)+ @store64(out_flags, PARENT)+ @store64(out_counter, 0)+ @store64(out_block_len, 64)+ }++ compress_into(+ out_cv,+ out_block,+ 0,+ @load64(out_block_len),+ @load64(out_flags) | ROOT,+ scratch+ )+ val j: mut usize = 0+ for j < 32 {+ val word: u64 = ldw(scratch, j / 4)+ val byte: u8 = ((word >> ((j % 4) * 8)) & 255) as u8+ @store8(@ptradd(out, j as i64), byte)+ j = j + 1+ }++ @free(stack as ref void)+ @free(scratch as ref void)+ @free(out_cv as ref void)+ @free(out_block as ref void)+ @free(out_flags as ref void)+ @free(out_counter as ref void)+ @free(out_block_len as ref void)+ @free(chunk_cv as ref void)+ @free(new_cv as ref void)+ @free(left as ref void)+ @free(cur_cv as ref void)+}--- /dev/null+++ b/src/src/io/files.sx@@ -0,0 +1,215 @@+/// Small filesystem helpers over the Spectre standard library.+///+/// Paths are borrowed `StringView` values. Functions that allocate a path+/// return a view whose storage is released with `free_path`.++val fs = use("std/fs")+val str = use("std/string")+val allocators = use("std/allocators")+val bytes = use("../core/bytes.sx")+val lists = use("../core/lists.sx")++pub val MAX_PATH: usize = 65536++fn heap() allocators.HeapAllocator = {+ return @zeroed+}++pub fn to_view(b: bytes.Bytes) str.StringView = {+ return str.view(b.ptr, b.len as i64)+}++pub fn cstr_view(b: bytes.Bytes) str.StringView = {+ return str.from_cstr(b.ptr)+}++/// Join two path components with a single separator when needed.+pub fn join(a: str.StringView, b: str.StringView) str.StringView = {+ val need_sep: mut usize = 0+ if a.len > 0 {+ val last: u8 = trust @load8(@ptradd(a.ptr, a.len - 1))+ if last != 47 {+ need_sep = 1+ }+ }+ val n: usize = a.len + need_sep + b.len+ val p: ref u8 = @alloc(n + 1) as ref u8+ trust {+ if a.len > 0 {+ @memcpy(p as ref void, a.ptr as ref void, a.len as usize)+ }+ if need_sep == 1 {+ @store8(@ptradd(p, a.len), 47)+ }+ if b.len > 0 {+ @memcpy(@ptradd(p, a.len + need_sep), b.ptr as ref void, b.len as usize)+ }+ @store8(@ptradd(p, n), 0)+ }+ return str.view(p, n)+}++/// Join three components. The caller owns the result.+pub fn join3(a: str.StringView, b: str.StringView, c: str.StringView) str.StringView = {+ val ab: str.StringView = join(a, b)+ val out: str.StringView = join(ab, c)+ free_path(ab)+ return out+}++pub fn free_path(p: str.StringView) void = {+ if p.ptr != none {+ val q: mut ref void = p.ptr as ref void+ trust @free(q)+ }+}++/// Append a literal suffix to a path, returning a newly allocated view.+pub fn with_suffix(p: str.StringView, suffix: str.StringView) str.StringView = {+ val n: usize = p.len + suffix.len+ val out: ref u8 = @alloc(n + 1) as ref u8+ trust {+ if p.len > 0 {+ @memcpy(out as ref void, p.ptr as ref void, p.len as usize)+ }+ if suffix.len > 0 {+ @memcpy(@ptradd(out, p.len), suffix.ptr as ref void, suffix.len as usize)+ }+ @store8(@ptradd(out, n), 0)+ }+ return str.view(out, n)+}++pub fn basename(p: str.StringView) str.StringView = {+ val i: mut i64 = p.len - 1+ for i >= 0 {+ val c: u8 = trust @load8(@ptradd(p.ptr, i))+ if c == 47 {+ return trust str.slice(p, i + 1, p.len)+ }+ i = i - 1+ }+ return p+}++pub fn exists_file(p: str.StringView) bool = {+ if trust fs.is_directory(p) {+ return false+ }+ val sz = trust fs.file_size(p)+ if sz is some _ {+ return true+ }+ return false+}++pub fn exists_dir(p: str.StringView) bool = {+ return trust fs.is_directory(p)+}++/// Read an entire file. The returned buffer is owned by the caller.+pub fn read_all(p: str.StringView) option[bytes.Bytes] = {+ val size_opt = trust fs.file_size(p)+ if size_opt is none {+ return none+ }+ val size: mut i64 = 0+ match size_opt {+ some s => {+ size = s+ }+ none => {+ return none+ }+ }+ if size < 0 || size > 1073741824 {+ return none+ }+ if size == 0 {+ return some bytes.empty()+ }+ val data_opt = trust fs.read_all_heap(p)+ if data_opt is none {+ return none+ }+ val ptr: mut ref u8 = none+ match data_opt {+ some p2 => {+ ptr = p2+ }+ none => {+ return none+ }+ }+ return some bytes.bytes(ptr, size as usize)+}++pub fn free_buffer(b: bytes.Bytes) void = {+ if b.ptr != none {+ val p: mut ref void = b.ptr as ref void+ trust @free(p)+ }+}++pub fn write_all(p: str.StringView, data: bytes.Bytes) bool = {+ return trust fs.write_all_bytes(p, data.ptr as ref void, data.len as i64)+}++pub fn append_all(p: str.StringView, data: bytes.Bytes) bool = {+ return trust fs.append_all_bytes(p, data.ptr as ref void, data.len as i64)+}++pub fn mkdir_all(p: str.StringView) bool = {+ return trust fs.mkdir_path(p)+}++pub fn delete(p: str.StringView) bool = {+ return trust fs.delete(p)+}++pub fn rename_path(oldp: str.StringView, newp: str.StringView) bool = {+ return trust fs.rename_path(oldp, newp)+}++/// List directory entry names. Each name is an owned NUL-terminated string.+/// The caller releases the result with `free_names`.+pub fn list_dir(p: str.StringView) list[ref u8] = {+ val z: str.ZString = trust str.zstr_from[allocators.HeapAllocator](heap(), p)+ if z.ptr == none {+ return lists.new[ref u8]()+ }+ val result = trust fs.walk_dir_cstr[allocators.HeapAllocator](heap(), z.ptr)+ trust str.zstr_free[allocators.HeapAllocator](heap(), z)+ if result is some names {+ return names+ }+ return lists.new[ref u8]()+}++pub fn free_names(names: list[ref u8]) void = {+ for n in names {+ val p: mut ref void = n as ref void+ trust @free(p)+ }+ @listfree(names)+}++/// True when a C string ends with the given ASCII suffix.+pub fn name_ends_with(name: ref u8, suffix: ref u8) bool = {+ val nl: i64 = @strlen(name)+ val sl: i64 = @strlen(suffix)+ if sl > nl {+ return false+ }+ val off: i64 = nl - sl+ val i: mut i64 = 0+ for i < sl {+ val a: u8 = trust @load8(@ptradd(name, off + i))+ val b: u8 = trust @load8(@ptradd(suffix, i))+ if a != b {+ return false+ }+ i = i + 1+ }+ return true+}--- /dev/null+++ b/src/src/io/native.sx@@ -0,0 +1,104 @@+/// Durable file writes used by the object store.+///+/// A pack is written to `store/tmp`, fsynced, renamed into `store/packs`, and+/// the containing directory is fsynced. The index follows the same procedure.++val str = use("std/string")+val allocators = use("std/allocators")+val bytes = use("../core/bytes.sx")++extern (C) fn open(path: ref u8, flags: i32, mode: i32) i32 = "open"+extern (C) fn write(fd: i32, buf: ref void, n: usize) i64 = "write"+extern (C) fn fsync(fd: i32) i32 = "fsync"+extern (C) fn close(fd: i32) i32 = "close"+extern (C) fn rename(oldpath: ref u8, newpath: ref u8) i32 = "rename"++val O_WRONLY: i32 = 1+val O_CREAT: i32 = 64+val O_TRUNC: i32 = 512+val OPEN_FLAGS: i32 = 577+val MODE: i32 = 420++fn heap() allocators.HeapAllocator = {+ return @zeroed+}++fn zstr(p: str.StringView) str.ZString = {+ return trust str.zstr_from[allocators.HeapAllocator](heap(), p)+}++fn free_z(z: str.ZString) void = {+ trust str.zstr_free[allocators.HeapAllocator](heap(), z)+}++fn write_all_fd(fd: i32, data: bytes.Bytes) bool = trust {+ val off: mut usize = 0+ for off < data.len {+ val p: ref void = @ptradd(data.ptr, off as i64) as ref void+ val n: i64 = write(fd, p, data.len - off)+ if n <= 0 {+ return false+ }+ off = off + n as usize+ }+ return true+}++fn sync_dir(dir: str.StringView) bool = {+ val z: str.ZString = zstr(dir)+ if z.ptr == none {+ return false+ }+ val success: mut bool = false+ trust {+ val fd: i32 = open(z.ptr, 0, 0)+ if fd >= 0 {+ val r: i32 = fsync(fd)+ close(fd)+ success = r == 0+ }+ }+ free_z(z)+ return success+}++/// Write `data` to `tmp`, fsync it, rename it to `final`, and fsync both+/// directories. Returns false on any failure.+pub fn write_atomic(+ tmp: str.StringView,+ final: str.StringView,+ tmp_dir: str.StringView,+ final_dir: str.StringView,+ data: bytes.Bytes+) bool = {+ val tz: str.ZString = zstr(tmp)+ val fz: str.ZString = zstr(final)+ if tz.ptr == none || fz.ptr == none {+ free_z(tz)+ free_z(fz)+ return false+ }+ val success: mut bool = false+ trust {+ val fd: i32 = open(tz.ptr, OPEN_FLAGS, MODE)+ if fd >= 0 {+ val wrote: bool = write_all_fd(fd, data)+ val synced: i32 = fsync(fd)+ close(fd)+ if wrote && synced == 0 {+ if rename(tz.ptr, fz.ptr) == 0 {+ success = true+ }+ }+ }+ }+ free_z(tz)+ free_z(fz)+ if !success {+ return false+ }+ if !sync_dir(tmp_dir) {+ return false+ }+ return sync_dir(final_dir)+}--- a/src/src/main.sx+++ b/src/src/main.sx@@ -1,5 +1,97 @@ val stdio = use("std/stdio")+val str = use("std/string")+val bytes = use("core/bytes.sx")+val init_cmd = use("cli/init_cmd.sx")+val fsck_cmd = use("cli/fsck_cmd.sx")+val selftest_cmd = use("cli/selftest_cmd.sx") -pub fn main() void = {- stdio.puts("Hello, world.")+fn cmd_is(a: ref u8, text: ref u8, len: usize) bool = {+ if a == none {+ return false+ }+ return bytes.Bytes.eql(bytes.from_cstr(a), bytes.bytes(text, len))+}++fn usage() void = trust {+ stdio.puts("vein - content-addressed version control")+ stdio.puts("")+ stdio.puts("usage: vn <command> [arguments]")+ stdio.puts("")+ stdio.puts("commands:")+ stdio.puts(" init [path] create a repository")+ stdio.puts(" fsck [path] [-v] verify pack, index, object, and op-log integrity")+ stdio.puts(" selftest run the M0 format self-tests")+ stdio.puts(" version print version information")+}++fn run_init(args: list[ref u8], start: usize) i32 = {+ val path_opt = @get(args, start)+ val mut_path: mut str.StringView = str.from_cstr(c".")+ match path_opt {+ some p => {+ mut_path = str.from_cstr(p)+ }+ none => {+ }+ }+ return init_cmd.run(mut_path)+}++fn run_fsck(args: list[ref u8], start: usize) i32 = trust {+ val mut_path: mut str.StringView = str.from_cstr(c".")+ val verbose: mut bool = false+ val i: mut usize = start+ for i < @len(args) {+ val o = @get(args, i)+ if o is some a {+ if cmd_is(a, c"-v", 2) || cmd_is(a, c"--verbose", 9) {+ verbose = true+ } else {+ mut_path = str.from_cstr(a)+ }+ }+ i = i + 1+ }+ return fsck_cmd.run(mut_path, verbose)+}++pub fn main() i32 = trust {+ val args: list[ref u8] = @args()+ if @len(args) < 2 {+ usage()+ return 1+ }+ val cmd_opt = @get(args, 1)+ val cmd: mut ref u8 = none+ match cmd_opt {+ some c => {+ cmd = c+ }+ none => {+ usage()+ return 1+ }+ }++ if cmd_is(cmd, c"init", 4) {+ return run_init(args, 2)+ }+ if cmd_is(cmd, c"fsck", 4) {+ return run_fsck(args, 2)+ }+ if cmd_is(cmd, c"selftest", 8) {+ return selftest_cmd.run()+ }+ if cmd_is(cmd, c"version", 7) || cmd_is(cmd, c"--version", 9) {+ stdio.puts("vn 0.0.1 (vein-store 1)")+ return 0+ }+ if cmd_is(cmd, c"help", 4) || cmd_is(cmd, c"--help", 6) {+ usage()+ return 0+ }++ stdio.eprint("vn: unknown command: {s}\n", {str.from_cstr(cmd)})+ usage()+ return 1 }--- /dev/null+++ b/src/src/object/blob.sx@@ -0,0 +1,290 @@+/// Blob objects: inline data or a tree of chunk/child references.+///+/// The builder applies the canonical rules in the specification: files up to+/// 16 KiB are inline, larger files are chunked with FastCDC, and manifest+/// levels are grouped by the ID-dependent boundary rule.++val bytes = use("../core/bytes.sx")+val buf = use("../core/buf.sx")+val reader = use("../core/reader.sx")+val derr = use("../core/error.sx")+val prim = use("../core/primitives.sx")+val lists = use("../core/lists.sx")+val objid = use("id.sx")+val types = use("types.sx")+val raw = use("raw.sx")+val fastcdc = use("../chunking/fastcdc.sx")++pub val FORM_INLINE: u8 = 0+pub val FORM_LEAF: u8 = 1+pub val FORM_INTERIOR: u8 = 2++pub type BlobEntry = {+ id: mut objid.Id+ length: mut u64+}++pub type Blob = {+ form: mut u8+ data: mut bytes.Bytes+ entries: mut list[ref BlobEntry]+}++pub type NodeRef = {+ id: mut ref u8+ length: mut u64+}++pub type BlobBuild = {+ root: mut ref u8+ root_body: mut bytes.Bytes+ objects: mut list[ref raw.RawObject]+}++/// The root blob ID. Stored as a raw pointer in `BlobBuild` so that returning+/// the build result does not depend on the representation of one-field structs.+pub fn root_id(b: ref BlobBuild) objid.Id = {+ return objid.id(b.root)+}++fn new_build(root: ref u8, root_body: bytes.Bytes, objects: list[ref raw.RawObject]) ref BlobBuild = {+ val b: mut ref BlobBuild = @alloc(@sizeof(BlobBuild)) as ref BlobBuild+ b.root = root+ b.root_body = root_body+ b.objects = objects+ return b+}++pub fn free_build(b: ref BlobBuild) void = {+ raw.free_objects(b.objects)+ val p: mut ref void = b as ref void+ trust @free(p)+}++fn new_entry(id: objid.Id, length: u64) ref BlobEntry = {+ val e: mut ref BlobEntry = @alloc(@sizeof(BlobEntry)) as ref BlobEntry+ e.id = id+ e.length = length+ return e+}++fn new_node(id: objid.Id, length: u64) ref NodeRef = {+ val n: mut ref NodeRef = @alloc(@sizeof(NodeRef)) as ref NodeRef+ n.id = id.ptr+ n.length = length+ return n+}++fn node_at(nodes: list[ref NodeRef], i: usize) ref NodeRef = {+ val o = @get(nodes, i)+ if o is some n {+ return n+ }+ assert false+ return none+}++pub fn free_blob(b: ref Blob) void = {+ for e in b.entries {+ val p: mut ref void = e as ref void+ trust @free(p)+ }+ @listfree(b.entries)+ trust @free(b as ref void)+}++/// Decode and validate a blob body.+pub fn decode(body: bytes.Bytes) result[ref Blob, derr.DecodeError] = {+ val r: mut reader.Reader = reader.new(body.ptr, body.len)+ val form: u8 = reader.Reader.read_u8(r)?+ if form > FORM_INTERIOR {+ return err derr.fail(derr.ErrorKind.InvalidValue, 0)+ }+ val b: mut ref Blob = @alloc(@sizeof(Blob)) as ref Blob+ b.form = form+ b.data = bytes.empty()+ b.entries = lists.new[ref BlobEntry]()++ if form == FORM_INLINE {+ b.data = reader.Reader.read_bytes(r, prim.INLINE_THRESHOLD)?+ reader.Reader.finish(r)?+ return ok b+ }++ val count: usize = reader.Reader.read_list_len(r, prim.MAX_MANIFEST_ENTRIES)?+ if count == 0 {+ return err derr.fail(derr.ErrorKind.InvalidValue, 1)+ }+ val total: mut u64 = 0+ val i: mut usize = 0+ for i < count {+ val at: usize = reader.Reader.offset(r)+ val cid: ref u8 = reader.Reader.read_id(r)?+ val length: u64 = reader.Reader.read_varint(r)?+ if length == 0 {+ return err derr.fail(derr.ErrorKind.InvalidValue, at)+ }+ if form == FORM_LEAF {+ if length > prim.MAX_CHUNK_LEN as u64 {+ return err derr.fail(derr.ErrorKind.LimitExceeded, at)+ }+ }+ val next_total: u64 = total + length+ if next_total < total {+ return err derr.fail(derr.ErrorKind.InvalidValue, at)+ }+ total = next_total+ @append(b.entries, new_entry(objid.id(cid), length))+ i = i + 1+ }+ reader.Reader.finish(r)?+ return ok b+}++/// True when a manifest node must end after an entry.+fn cut_after(entry_id: ref u8, current_len: usize) bool = {+ if current_len >= prim.MAX_MANIFEST_ENTRIES {+ return true+ }+ if current_len < 16 {+ return false+ }+ val first: u8 = trust @load8(entry_id)+ return first == 0+}++pub type Group = {+ start: mut usize+ count: mut usize+}++fn new_group(start: usize, count: usize) ref Group = {+ val g: mut ref Group = @alloc(@sizeof(Group)) as ref Group+ g.start = start+ g.count = count+ return g+}++fn group_nodes(nodes: list[ref NodeRef]) list[ref Group] = {+ val out: mut list[ref Group] = lists.new[ref Group]()+ val n: usize = @len(nodes)+ if n == 0 {+ return out+ }+ val start: mut usize = 0+ val i: mut usize = 0+ for i < n {+ val node = node_at(nodes, i)+ val current: usize = i - start + 1+ if cut_after(node.id, current) || i + 1 == n {+ @append(out, new_group(start, current))+ start = i + 1+ }+ i = i + 1+ }+ return out+}++fn build_node_body(nodes: list[ref NodeRef], group: ref Group, form: u8) buf.Buf = {+ val b: mut buf.Buf = buf.new(group.count * 40 + 8)+ buf.Buf.put_u8(b, form)+ buf.Buf.put_varint(b, group.count as u64)+ val i: mut usize = 0+ for i < group.count {+ val node = node_at(nodes, group.start + i)+ buf.Buf.put_id(b, node.id)+ buf.Buf.put_varint(b, node.length)+ i = i + 1+ }+ return b+}++fn sum_group(nodes: list[ref NodeRef], group: ref Group) u64 = {+ val total: mut u64 = 0+ val i: mut usize = 0+ for i < group.count {+ total = total + node_at(nodes, group.start + i).length+ i = i + 1+ }+ return total+}++fn free_groups(groups: list[ref Group]) void = {+ for g in groups {+ val p: mut ref void = g as ref void+ trust @free(p)+ }+ @listfree(groups)+}++fn free_nodes(nodes: list[ref NodeRef]) void = {+ for n in nodes {+ val p: mut ref void = n as ref void+ trust @free(p)+ }+ @listfree(nodes)+}++/// Chunk and manifest a file. All produced objects, including chunks, are+/// returned in `objects`; the caller owns them.+pub fn build(data: ref u8, len: usize) ref BlobBuild = {+ val objects: mut list[ref raw.RawObject] = raw.empty_list()+ if len <= prim.INLINE_THRESHOLD {+ val b: mut buf.Buf = buf.new(len + 16)+ buf.Buf.put_u8(b, FORM_INLINE)+ buf.Buf.put_length_prefixed(b, bytes.bytes(data, len))+ val body: bytes.Bytes = buf.Buf.view(b)+ val root: objid.Id = objid.object_id(types.BLOB, body)+ val owned: bytes.Bytes = bytes.Bytes.dup(body)+ @append(objects, raw.raw(types.BLOB, owned))+ buf.Buf.free(b)+ return new_build(root.ptr, owned, objects)+ }++ val level: mut list[ref NodeRef] = lists.new[ref NodeRef]()+ val off: mut usize = 0+ for off < len {+ val n: usize = fastcdc.next_len(trust @ptradd(data, off as i64), len - off)+ val chunk: bytes.Bytes = bytes.Bytes.slice(bytes.bytes(data, len), off, off + n)+ val cid: objid.Id = objid.object_id(types.CHUNK, chunk)+ @append(objects, raw.raw(types.CHUNK, chunk))+ @append(level, new_node(cid, n as u64))+ off = off + n+ }++ val root_id: mut objid.Id = objid.id_none()+ val root_body: mut bytes.Bytes = bytes.empty()+ val leaf_level: mut bool = true+ for {+ val groups: list[ref Group] = group_nodes(level)+ val next: mut list[ref NodeRef] = lists.new[ref NodeRef]()+ val last_body: mut bytes.Bytes = bytes.empty()+ for g in groups {+ val node_form: mut u8 = FORM_INTERIOR+ if leaf_level {+ node_form = FORM_LEAF+ }+ val b: mut buf.Buf = build_node_body(level, g, node_form)+ val body: bytes.Bytes = buf.Buf.view(b)+ val nid: objid.Id = objid.object_id(types.BLOB, body)+ val owned: bytes.Bytes = bytes.Bytes.dup(body)+ @append(objects, raw.raw(types.BLOB, owned))+ @append(next, new_node(nid, sum_group(level, g)))+ last_body = owned+ buf.Buf.free(b)+ }+ free_groups(groups)+ free_nodes(level)+ if @len(next) == 1 {+ val only = node_at(next, 0)+ root_id = objid.id(only.id)+ root_body = last_body+ free_nodes(next)+ break+ }+ level = next+ leaf_level = false+ }++ return new_build(root_id.ptr, root_body, objects)+}--- /dev/null+++ b/src/src/object/commit.sx@@ -0,0 +1,222 @@+/// Commit objects.++val bytes = use("../core/bytes.sx")+val buf = use("../core/buf.sx")+val reader = use("../core/reader.sx")+val derr = use("../core/error.sx")+val prim = use("../core/primitives.sx")+val lists = use("../core/lists.sx")+val objid = use("id.sx")+val names = use("names.sx")++pub val RENAMES_UNKNOWN: u8 = 0+pub val RENAMES_RECORDED: u8 = 1++pub type Rename = {+ parent_index: mut u64+ kind: mut u8+ from_path: mut bytes.Bytes+ to_path: mut bytes.Bytes+}++pub type Commit = {+ version: mut u8+ parents: mut list[objid.Id]+ root_tree: mut objid.Id+ change_id: mut objid.ChangeId+ author: mut prim.Sig+ committer: mut prim.Sig+ message: mut bytes.Bytes+ renames_state: mut u8+ renames: mut list[ref Rename]+ extra: mut list[ref prim.KeyValue]+}++pub fn new_rename(+ parent_index: u64,+ kind: u8,+ from_path: bytes.Bytes,+ to_path: bytes.Bytes+) ref Rename = {+ val r: mut ref Rename = @alloc(@sizeof(Rename)) as ref Rename+ r.parent_index = parent_index+ r.kind = kind+ r.from_path = from_path+ r.to_path = to_path+ return r+}++pub fn new_kv(key: bytes.Bytes, value: bytes.Bytes) ref prim.KeyValue = {+ val kv: mut ref prim.KeyValue = @alloc(@sizeof(prim.KeyValue)) as ref prim.KeyValue+ kv.key = key+ kv.value = value+ return kv+}++fn id_at(ids: list[objid.Id], i: usize) objid.Id = {+ val o = @get(ids, i)+ if o is some v {+ return v+ }+ assert false+ return objid.id_none()+}++fn read_parents(r: mut reader.Reader) result[list[objid.Id], derr.DecodeError] = {+ val n: usize = reader.Reader.read_list_len(r, 1024)?+ val out: mut list[objid.Id] = lists.new[objid.Id]()+ val i: mut usize = 0+ for i < n {+ val p: ref u8 = reader.Reader.read_id(r)?+ @append(out, objid.id(p))+ i = i + 1+ }+ return ok out+}++fn read_renames(+ r: mut reader.Reader,+ parent_count: usize,+ state: u8+) result[list[ref Rename], derr.DecodeError] = {+ val n: usize = reader.Reader.read_list_len(r, 1000000)?+ val out: mut list[ref Rename] = lists.new[ref Rename]()+ if state == RENAMES_UNKNOWN {+ if n != 0 {+ return err derr.fail(derr.ErrorKind.InvalidValue, reader.Reader.offset(r))+ }+ return ok out+ }+ val prev_parent: mut u64 = 0+ val prev_path: mut bytes.Bytes = bytes.empty()+ val have_prev: mut bool = false+ val i: mut usize = 0+ for i < n {+ val at: usize = reader.Reader.offset(r)+ val parent_index: u64 = reader.Reader.read_varint(r)?+ val kind: u8 = reader.Reader.read_u8(r)?+ val from: bytes.Bytes = reader.Reader.read_bytes(r, prim.MAX_PATH_LEN)?+ val to: bytes.Bytes = reader.Reader.read_bytes(r, prim.MAX_PATH_LEN)?+ if parent_index >= parent_count as u64 {+ return err derr.fail(derr.ErrorKind.InvalidValue, at)+ }+ if kind > 1 {+ return err derr.fail(derr.ErrorKind.InvalidValue, at)+ }+ if !names.valid_path(from) || !names.valid_path(to) {+ return err derr.fail(derr.ErrorKind.InvalidName, at)+ }+ if have_prev {+ if parent_index < prev_parent {+ return err derr.fail(derr.ErrorKind.Unsorted, at)+ }+ if parent_index == prev_parent && bytes.Bytes.cmp(prev_path, to) >= 0 {+ return err derr.fail(derr.ErrorKind.Unsorted, at)+ }+ }+ @append(out, new_rename(parent_index, kind, from, to))+ prev_parent = parent_index+ prev_path = to+ have_prev = true+ i = i + 1+ }+ return ok out+}++fn read_extra(r: mut reader.Reader) result[list[ref prim.KeyValue], derr.DecodeError] = {+ val n: usize = reader.Reader.read_list_len(r, 1024)?+ val out: mut list[ref prim.KeyValue] = lists.new[ref prim.KeyValue]()+ val i: mut usize = 0+ for i < n {+ val at: usize = reader.Reader.offset(r)+ val key: bytes.Bytes = reader.Reader.read_bytes(r, prim.MAX_NAME_LEN)?+ val value: bytes.Bytes = reader.Reader.read_bytes(r, prim.MAX_MESSAGE_LEN)?+ if key.len == 0 {+ return err derr.fail(derr.ErrorKind.InvalidValue, at)+ }+ @append(out, new_kv(key, value))+ i = i + 1+ }+ return ok out+}++pub fn decode(body: bytes.Bytes) result[ref Commit, derr.DecodeError] = {+ val r: mut reader.Reader = reader.new(body.ptr, body.len)+ val c: mut ref Commit = @alloc(@sizeof(Commit)) as ref Commit+ c.version = reader.Reader.read_u8(r)?+ if c.version != 1 {+ return err derr.fail(derr.ErrorKind.UnsupportedVersion, 0)+ }+ c.parents = read_parents(r)?+ val root: ref u8 = reader.Reader.read_id(r)?+ c.root_tree = objid.id(root)+ val cid: bytes.Bytes = reader.Reader.read_raw(r, 16)?+ c.change_id = objid.change_id(cid.ptr)+ c.author = reader.Reader.read_sig(r, prim.MAX_NAME_LEN, prim.MAX_NAME_LEN)?+ c.committer = reader.Reader.read_sig(r, prim.MAX_NAME_LEN, prim.MAX_NAME_LEN)?+ c.message = reader.Reader.read_bytes(r, prim.MAX_MESSAGE_LEN)?+ c.renames_state = reader.Reader.read_u8(r)?+ if c.renames_state > 1 {+ return err derr.fail(derr.ErrorKind.InvalidValue, reader.Reader.offset(r) - 1)+ }+ c.renames = read_renames(r, @len(c.parents), c.renames_state)?+ c.extra = read_extra(r)?+ reader.Reader.finish(r)?+ return ok c+}++pub fn encode(c: ref Commit) bytes.Bytes = {+ val b: mut buf.Buf = buf.new(256)+ buf.Buf.put_u8(b, c.version)+ buf.Buf.put_varint(b, @len(c.parents) as u64)+ val i: mut usize = 0+ for i < @len(c.parents) {+ buf.Buf.put_id(b, id_at(c.parents, i).ptr)+ i = i + 1+ }+ buf.Buf.put_id(b, c.root_tree.ptr)+ buf.Buf.put_raw(b, c.change_id.ptr, 16)+ buf.Buf.put_sig(b, c.author)+ buf.Buf.put_sig(b, c.committer)+ buf.Buf.put_length_prefixed(b, c.message)+ buf.Buf.put_u8(b, c.renames_state)+ buf.Buf.put_varint(b, @len(c.renames) as u64)+ for rn in c.renames {+ buf.Buf.put_varint(b, rn.parent_index)+ buf.Buf.put_u8(b, rn.kind)+ buf.Buf.put_length_prefixed(b, rn.from_path)+ buf.Buf.put_length_prefixed(b, rn.to_path)+ }+ buf.Buf.put_varint(b, @len(c.extra) as u64)+ for kv in c.extra {+ buf.Buf.put_length_prefixed(b, kv.key)+ buf.Buf.put_length_prefixed(b, kv.value)+ }+ val out: bytes.Bytes = bytes.Bytes.dup(buf.Buf.view(b))+ buf.Buf.free(b)+ return out+}++fn free_renames(rs: list[ref Rename]) void = {+ for r in rs {+ val p: mut ref void = r as ref void+ trust @free(p)+ }+ @listfree(rs)+}++fn free_kvs(xs: list[ref prim.KeyValue]) void = {+ for kv in xs {+ val p: mut ref void = kv as ref void+ trust @free(p)+ }+ @listfree(xs)+}++pub fn free_commit(c: ref Commit) void = {+ @listfree(c.parents)+ free_renames(c.renames)+ free_kvs(c.extra)+ val p: mut ref void = c as ref void+ trust @free(p)+}--- /dev/null+++ b/src/src/object/conflict.sx@@ -0,0 +1,168 @@+/// Conflict objects: a simplified signed sum of tree-entry values.++val bytes = use("../core/bytes.sx")+val buf = use("../core/buf.sx")+val reader = use("../core/reader.sx")+val derr = use("../core/error.sx")+val prim = use("../core/primitives.sx")+val lists = use("../core/lists.sx")+val objid = use("id.sx")++pub val VALUE_ABSENT: u8 = 0++pub type ConflictValue = {+ kind: mut u8+ target: mut objid.Id+}++pub type Conflict = {+ adds: mut list[ref ConflictValue]+ removes: mut list[ref ConflictValue]+}++pub fn value_absent() ref ConflictValue = {+ val v: mut ref ConflictValue = @alloc(@sizeof(ConflictValue)) as ref ConflictValue+ v.kind = VALUE_ABSENT+ v.target = objid.id_none()+ return v+}++pub fn value(kind: u8, target: objid.Id) ref ConflictValue = {+ val v: mut ref ConflictValue = @alloc(@sizeof(ConflictValue)) as ref ConflictValue+ v.kind = kind+ v.target = target+ return v+}++pub fn (ConflictValue) eql(a: self, b: ref ConflictValue) bool = {+ if a.kind != b.kind {+ return false+ }+ if a.kind == VALUE_ABSENT {+ return true+ }+ return objid.Id.eql(a.target, b.target)+}++fn value_kind_valid(k: u8) bool = {+ return k == 0 || (k >= 1 && k <= 6)+}++fn read_value(r: mut reader.Reader) result[ref ConflictValue, derr.DecodeError] = {+ val at: usize = reader.Reader.offset(r)+ val kind: u8 = reader.Reader.read_u8(r)?+ if !value_kind_valid(kind) {+ return err derr.fail(derr.ErrorKind.InvalidValue, at)+ }+ if kind == VALUE_ABSENT {+ return ok value_absent()+ }+ val target: ref u8 = reader.Reader.read_id(r)?+ return ok value(kind, objid.id(target))+}++fn read_values(+ r: mut reader.Reader,+ max: usize+) result[list[ref ConflictValue], derr.DecodeError] = {+ val n: usize = reader.Reader.read_list_len(r, max)?+ val out: mut list[ref ConflictValue] = lists.new[ref ConflictValue]()+ val i: mut usize = 0+ for i < n {+ @append(out, read_value(r)?)+ i = i + 1+ }+ return ok out+}++fn contains(vals: list[ref ConflictValue], v: ref ConflictValue) bool = {+ for x in vals {+ if ConflictValue.eql(x, v) {+ return true+ }+ }+ return false+}++fn all_same(vals: list[ref ConflictValue]) bool = {+ if @len(vals) <= 1 {+ return true+ }+ val first = @get(vals, 0)+ if first is some f {+ for x in vals {+ if !ConflictValue.eql(f, x) {+ return false+ }+ }+ return true+ }+ return true+}++pub fn decode(body: bytes.Bytes) result[ref Conflict, derr.DecodeError] = {+ val r: mut reader.Reader = reader.new(body.ptr, body.len)+ val c: mut ref Conflict = @alloc(@sizeof(Conflict)) as ref Conflict+ c.adds = read_values(r, prim.MAX_CONFLICT_TERMS)?+ c.removes = read_values(r, prim.MAX_CONFLICT_TERMS)?+ val at: usize = reader.Reader.offset(r)+ reader.Reader.finish(r)?++ if @len(c.removes) == 0 {+ return err derr.fail(derr.ErrorKind.InvalidValue, at)+ }+ if @len(c.adds) != @len(c.removes) + 1 {+ return err derr.fail(derr.ErrorKind.InvalidValue, at)+ }+ if @len(c.adds) + @len(c.removes) > prim.MAX_CONFLICT_TERMS {+ return err derr.fail(derr.ErrorKind.LimitExceeded, at)+ }+ for a in c.adds {+ if contains(c.removes, a) {+ return err derr.fail(derr.ErrorKind.InvalidValue, at)+ }+ }+ if all_same(c.adds) {+ return err derr.fail(derr.ErrorKind.InvalidValue, at)+ }+ return ok c+}++pub fn encode(+ adds: list[ref ConflictValue],+ removes: list[ref ConflictValue]+) bytes.Bytes = {+ val b: mut buf.Buf = buf.new((@len(adds) + @len(removes)) * 40 + 16)+ buf.Buf.put_varint(b, @len(adds) as u64)+ for v in adds {+ buf.Buf.put_u8(b, v.kind)+ if v.kind != VALUE_ABSENT {+ buf.Buf.put_id(b, v.target.ptr)+ }+ }+ buf.Buf.put_varint(b, @len(removes) as u64)+ for v in removes {+ buf.Buf.put_u8(b, v.kind)+ if v.kind != VALUE_ABSENT {+ buf.Buf.put_id(b, v.target.ptr)+ }+ }+ val out: bytes.Bytes = bytes.Bytes.dup(buf.Buf.view(b))+ buf.Buf.free(b)+ return out+}++pub fn free_conflict(c: ref Conflict) void = {+ for v in c.adds {+ val p: mut ref void = v as ref void+ trust @free(p)+ }+ for v in c.removes {+ val p: mut ref void = v as ref void+ trust @free(p)+ }+ @listfree(c.adds)+ @listfree(c.removes)+ val p2: mut ref void = c as ref void+ trust @free(p2)+}--- /dev/null+++ b/src/src/object/id.sx@@ -0,0 +1,164 @@+/// Content-addressed object identifiers and change identifiers.+///+/// IDs are borrowed views over 32 raw bytes (16 for change IDs). A decoder+/// points into the object body; an encoder points into a caller-owned buffer.++val bytes = use("../core/bytes.sx")+val buf = use("../core/buf.sx")+val b3 = use("../crypto/blake3.sx")++pub type Id = {+ ptr: ref u8+}+pub type ChangeId = {+ ptr: ref u8+}+pub val ID_LEN: usize = 32+pub val CHANGE_ID_LEN: usize = 16++pub fn id_none() Id = {+ return Id{ptr: none}+}++pub fn id(ptr: ref u8) Id = {+ return Id{ptr: ptr}+}++pub fn change_id(ptr: ref u8) ChangeId = {+ return ChangeId{ptr: ptr}+}++pub fn (Id) is_none(v: self) bool = {+ return v.ptr == none+}++pub fn (Id) eql(a: self, b: Id) bool = {+ if a.ptr == none || b.ptr == none {+ return a.ptr == b.ptr+ }+ return bytes.Bytes.eql(bytes.bytes(a.ptr, ID_LEN), bytes.bytes(b.ptr, ID_LEN))+}++pub fn (Id) cmp(a: self, b: Id) i64 = {+ if a.ptr == none {+ if b.ptr == none {+ return 0+ }+ return -1+ }+ if b.ptr == none {+ return 1+ }+ return bytes.Bytes.cmp(bytes.bytes(a.ptr, ID_LEN), bytes.bytes(b.ptr, ID_LEN))+}++pub fn (ChangeId) eql(a: self, b: ChangeId) bool = {+ if a.ptr == none || b.ptr == none {+ return a.ptr == b.ptr+ }+ return bytes.Bytes.eql(bytes.bytes(a.ptr, CHANGE_ID_LEN), bytes.bytes(b.ptr, CHANGE_ID_LEN))+}++pub fn (ChangeId) cmp(a: self, b: ChangeId) i64 = {+ if a.ptr == none {+ if b.ptr == none {+ return 0+ }+ return -1+ }+ if b.ptr == none {+ return 1+ }+ return bytes.Bytes.cmp(bytes.bytes(a.ptr, CHANGE_ID_LEN), bytes.bytes(b.ptr, CHANGE_ID_LEN))+}++fn hex_digit(n: u8) u8 = {+ if n < 10 {+ return (48 + n) as u8+ }+ return (87 + n) as u8+}++pub fn hex_encode(src: ref u8, n: usize, out: ref u8) void = {+ val i: mut usize = 0+ for i < n {+ trust {+ val v: u8 = @load8(@ptradd(src, i as i64))+ @store8(@ptradd(out, (i * 2) as i64), hex_digit(v >> 4))+ @store8(@ptradd(out, (i * 2 + 1) as i64), hex_digit(v & 15))+ }+ i = i + 1+ }+}++fn hex_value(c: u8) i32 = {+ if c >= 48 && c <= 57 {+ return (c - 48) as i32+ }+ if c >= 97 && c <= 102 {+ return (c - 87) as i32+ }+ if c >= 65 && c <= 70 {+ return (c - 55) as i32+ }+ return -1+}++/// Parse exactly `n * 2` hex characters into `n` bytes.+pub fn hex_decode(s: ref u8, n: usize, out: ref u8) bool = {+ val i: mut usize = 0+ for i < n {+ val hi: i32 = trust hex_value(@load8(@ptradd(s, (i * 2) as i64)))+ val lo: i32 = trust hex_value(@load8(@ptradd(s, (i * 2 + 1) as i64)))+ if hi < 0 || lo < 0 {+ return false+ }+ trust @store8(@ptradd(out, i as i64), ((hi * 16 + lo) as u8))+ i = i + 1+ }+ return true+}++/// Allocate a NUL-terminated 64-character hex string for an ID.+pub fn (Id) hex(v: self) ref u8 = {+ pre {+ present: v.ptr != none+ }+ val out: ref u8 = @alloc(65) as ref u8+ hex_encode(v.ptr, ID_LEN, out)+ trust @store8(@ptradd(out, 64), 0)+ return out+}++/// Allocate a NUL-terminated 32-character hex string for a change ID.+pub fn (ChangeId) hex(v: self) ref u8 = {+ pre {+ present: v.ptr != none+ }+ val out: ref u8 = @alloc(33) as ref u8+ hex_encode(v.ptr, CHANGE_ID_LEN, out)+ trust @store8(@ptradd(out, 32), 0)+ return out+}++/// Object ID domain separator and type byte, then the body.+pub fn object_id_into(type_byte: u8, body: bytes.Bytes, out: ref u8) void = {+ val b: mut buf.Buf = buf.new(body.len + 8)+ buf.Buf.put_raw(b, c"vein/1", 6)+ buf.Buf.put_u8(b, 0)+ buf.Buf.put_u8(b, type_byte)+ buf.Buf.put_bytes(b, body)+ trust b3.hash(b.ptr, b.len, out)+ buf.Buf.free(b)+}++/// Return a freshly allocated object ID. The caller owns the 32 bytes.+pub fn object_id(type_byte: u8, body: bytes.Bytes) Id = {+ val out: ref u8 = @alloc(ID_LEN) as ref u8+ object_id_into(type_byte, body, out)+ return Id{ptr: out}+}++pub fn id_from_bytes(type_byte: u8, body: bytes.Bytes) Id = {+ return object_id(type_byte, body)+}--- /dev/null+++ b/src/src/object/names.sx@@ -0,0 +1,81 @@+/// Name and path validation from the data model.++val bytes = use("../core/bytes.sx")+val prim = use("../core/primitives.sx")++fn is_dot_name(b: bytes.Bytes) bool = {+ if b.len == 1 && bytes.Bytes.at(b, 0) == 46 {+ return true+ }+ if b.len == 2 && bytes.Bytes.at(b, 0) == 46 && bytes.Bytes.at(b, 1) == 46 {+ return true+ }+ return false+}++/// A tree entry name: non-empty, not `.` or `..`, no `/` or NUL, and not+/// `.vein` in any case.+pub fn valid_name(b: bytes.Bytes) bool = {+ if b.len == 0 || b.len > prim.MAX_NAME_LEN {+ return false+ }+ val i: mut usize = 0+ for i < b.len {+ val c: u8 = bytes.Bytes.at(b, i)+ if c == 0 || c == 47 {+ return false+ }+ i = i + 1+ }+ if is_dot_name(b) {+ return false+ }+ val vein: bytes.Bytes = bytes.bytes(c".vein", 5)+ if bytes.Bytes.eql_ascii_ci(b, vein) {+ return false+ }+ return true+}++fn valid_component(b: bytes.Bytes) bool = {+ if b.len == 0 || b.len > prim.MAX_NAME_LEN {+ return false+ }+ if is_dot_name(b) {+ return false+ }+ val i: mut usize = 0+ for i < b.len {+ val c: u8 = bytes.Bytes.at(b, i)+ if c == 0 || c == 47 {+ return false+ }+ i = i + 1+ }+ return true+}++/// A '/'-separated relative path with no empty, `.`, or `..` components.+pub fn valid_path(p: bytes.Bytes) bool = {+ if p.len == 0 || p.len > prim.MAX_PATH_LEN {+ return false+ }+ if bytes.Bytes.at(p, 0) == 47 {+ return false+ }+ val start: mut usize = 0+ val i: mut usize = 0+ for i <= p.len {+ val at_end: bool = i == p.len+ val sep: bool = !at_end && bytes.Bytes.at(p, i) == 47+ if at_end || sep {+ val comp: bytes.Bytes = bytes.Bytes.slice(p, start, i)+ if !valid_component(comp) {+ return false+ }+ start = i + 1+ }+ i = i + 1+ }+ return true+}--- /dev/null+++ b/src/src/object/operation.sx@@ -0,0 +1,116 @@+/// Operation log records.++val bytes = use("../core/bytes.sx")+val buf = use("../core/buf.sx")+val reader = use("../core/reader.sx")+val derr = use("../core/error.sx")+val prim = use("../core/primitives.sx")+val lists = use("../core/lists.sx")+val objid = use("id.sx")++pub type Operation = {+ parents: mut list[objid.Id]+ view: mut objid.Id+ start: mut prim.TimeMs+ end: mut prim.TimeMs+ hostname: mut bytes.Bytes+ username: mut bytes.Bytes+ description: mut bytes.Bytes+ tags: mut list[ref prim.KeyValue]+}++fn new_kv(key: bytes.Bytes, value: bytes.Bytes) ref prim.KeyValue = {+ val kv: mut ref prim.KeyValue = @alloc(@sizeof(prim.KeyValue)) as ref prim.KeyValue+ kv.key = key+ kv.value = value+ return kv+}++fn read_parents(r: mut reader.Reader) result[list[objid.Id], derr.DecodeError] = {+ val n: usize = reader.Reader.read_list_len(r, 1024)?+ val out: mut list[objid.Id] = lists.new[objid.Id]()+ val i: mut usize = 0+ for i < n {+ val p: ref u8 = reader.Reader.read_id(r)?+ @append(out, objid.id(p))+ i = i + 1+ }+ return ok out+}++fn read_tags(r: mut reader.Reader) result[list[ref prim.KeyValue], derr.DecodeError] = {+ val n: usize = reader.Reader.read_list_len(r, 1024)?+ val out: mut list[ref prim.KeyValue] = lists.new[ref prim.KeyValue]()+ val i: mut usize = 0+ for i < n {+ val at: usize = reader.Reader.offset(r)+ val key: bytes.Bytes = reader.Reader.read_bytes(r, prim.MAX_NAME_LEN)?+ val value: bytes.Bytes = reader.Reader.read_bytes(r, prim.MAX_MESSAGE_LEN)?+ if key.len == 0 {+ return err derr.fail(derr.ErrorKind.InvalidValue, at)+ }+ @append(out, new_kv(key, value))+ i = i + 1+ }+ return ok out+}++pub fn decode(body: bytes.Bytes) result[ref Operation, derr.DecodeError] = {+ val r: mut reader.Reader = reader.new(body.ptr, body.len)+ val op: mut ref Operation = @alloc(@sizeof(Operation)) as ref Operation+ op.parents = read_parents(r)?+ val v: ref u8 = reader.Reader.read_id(r)?+ op.view = objid.id(v)+ op.start = reader.Reader.read_time_ms(r)?+ op.end = reader.Reader.read_time_ms(r)?+ op.hostname = reader.Reader.read_bytes(r, prim.MAX_NAME_LEN)?+ op.username = reader.Reader.read_bytes(r, prim.MAX_NAME_LEN)?+ op.description = reader.Reader.read_bytes(r, prim.MAX_MESSAGE_LEN)?+ op.tags = read_tags(r)?+ reader.Reader.finish(r)?+ return ok op+}++fn id_at(ids: list[objid.Id], i: usize) objid.Id = {+ val o = @get(ids, i)+ if o is some v {+ return v+ }+ assert false+ return objid.id_none()+}++pub fn encode(op: ref Operation) bytes.Bytes = {+ val b: mut buf.Buf = buf.new(256)+ buf.Buf.put_varint(b, @len(op.parents) as u64)+ val i: mut usize = 0+ for i < @len(op.parents) {+ buf.Buf.put_id(b, id_at(op.parents, i).ptr)+ i = i + 1+ }+ buf.Buf.put_id(b, op.view.ptr)+ buf.Buf.put_time_ms(b, op.start)+ buf.Buf.put_time_ms(b, op.end)+ buf.Buf.put_length_prefixed(b, op.hostname)+ buf.Buf.put_length_prefixed(b, op.username)+ buf.Buf.put_length_prefixed(b, op.description)+ buf.Buf.put_varint(b, @len(op.tags) as u64)+ for kv in op.tags {+ buf.Buf.put_length_prefixed(b, kv.key)+ buf.Buf.put_length_prefixed(b, kv.value)+ }+ val out: bytes.Bytes = bytes.Bytes.dup(buf.Buf.view(b))+ buf.Buf.free(b)+ return out+}++pub fn free_operation(op: ref Operation) void = {+ @listfree(op.parents)+ for kv in op.tags {+ val p: mut ref void = kv as ref void+ trust @free(p)+ }+ @listfree(op.tags)+ val p2: mut ref void = op as ref void+ trust @free(p2)+}--- /dev/null+++ b/src/src/object/raw.sx@@ -0,0 +1,32 @@+/// An untrusted body paired with its object type tag.++val bytes = use("../core/bytes.sx")+val lists = use("../core/lists.sx")++pub type RawObject = {+ type_byte: mut u8+ body: mut bytes.Bytes+}++pub fn raw(type_byte: u8, body: bytes.Bytes) ref RawObject = {+ val o: mut ref RawObject = @alloc(@sizeof(RawObject)) as ref RawObject+ o.type_byte = type_byte+ o.body = body+ return o+}++pub fn free_objects(objects: list[ref RawObject]) void = {+ for o in objects {+ if o.type_byte != 1 {+ val body_ptr: mut ref void = o.body.ptr as ref void+ trust @free(body_ptr)+ }+ val obj_ptr: mut ref void = o as ref void+ trust @free(obj_ptr)+ }+ @listfree(objects)+}++pub fn empty_list() list[ref RawObject] = {+ return lists.new[ref RawObject]()+}--- /dev/null+++ b/src/src/object/tree.sx@@ -0,0 +1,149 @@+/// Tree objects: sorted, unique directory entries.++val bytes = use("../core/bytes.sx")+val buf = use("../core/buf.sx")+val reader = use("../core/reader.sx")+val derr = use("../core/error.sx")+val prim = use("../core/primitives.sx")+val lists = use("../core/lists.sx")+val objid = use("id.sx")+val names = use("names.sx")++pub val KIND_FILE: u8 = 1+pub val KIND_EXECUTABLE: u8 = 2+pub val KIND_SYMLINK: u8 = 3+pub val KIND_SUBTREE: u8 = 4+pub val KIND_SUBMODULE: u8 = 5+pub val KIND_CONFLICT: u8 = 6++pub type TreeEntry = {+ name: mut bytes.Bytes+ kind: mut u8+ target: mut objid.Id+}++pub type Tree = {+ entries: mut list[ref TreeEntry]+}++pub fn entry(name: bytes.Bytes, kind: u8, target: objid.Id) ref TreeEntry = {+ val e: mut ref TreeEntry = @alloc(@sizeof(TreeEntry)) as ref TreeEntry+ e.name = name+ e.kind = kind+ e.target = target+ return e+}++pub fn empty() Tree = {+ return Tree{entries: lists.new[ref TreeEntry]()}+}++fn entry_at(entries: list[ref TreeEntry], i: usize) ref TreeEntry = {+ val o = @get(entries, i)+ if o is some e {+ return e+ }+ assert false+ return none+}++fn valid_kind(k: u8) bool = {+ return k >= KIND_FILE && k <= KIND_CONFLICT+}++fn valid_submodule(id: objid.Id) bool = {+ val i: mut usize = 20+ for i < 32 {+ if trust @load8(@ptradd(id.ptr, i as i64)) != 0 {+ return false+ }+ i = i + 1+ }+ return true+}++pub fn decode(body: bytes.Bytes) result[ref Tree, derr.DecodeError] = {+ val r: mut reader.Reader = reader.new(body.ptr, body.len)+ val count: usize = reader.Reader.read_list_len(r, prim.MAX_TREE_ENTRIES)?+ val t: mut ref Tree = @alloc(@sizeof(Tree)) as ref Tree+ t.entries = lists.new[ref TreeEntry]()+ val prev: mut bytes.Bytes = bytes.empty()+ val have_prev: mut bool = false+ val i: mut usize = 0+ for i < count {+ val at: usize = reader.Reader.offset(r)+ val name: bytes.Bytes = reader.Reader.read_bytes(r, prim.MAX_NAME_LEN)?+ if !names.valid_name(name) {+ return err derr.fail(derr.ErrorKind.InvalidName, at)+ }+ if have_prev {+ val c: i64 = bytes.Bytes.cmp(prev, name)+ if c == 0 {+ return err derr.fail(derr.ErrorKind.Duplicate, at)+ }+ if c > 0 {+ return err derr.fail(derr.ErrorKind.Unsorted, at)+ }+ }+ val kind: u8 = reader.Reader.read_u8(r)?+ if !valid_kind(kind) {+ return err derr.fail(derr.ErrorKind.InvalidValue, at)+ }+ val tid: ref u8 = reader.Reader.read_id(r)?+ if kind == KIND_SUBMODULE {+ if !valid_submodule(objid.id(tid)) {+ return err derr.fail(derr.ErrorKind.InvalidValue, at)+ }+ }+ @append(t.entries, entry(name, kind, objid.id(tid)))+ prev = name+ have_prev = true+ i = i + 1+ }+ reader.Reader.finish(r)?+ return ok t+}++/// Encode entries in the order given. The caller is responsible for sorting;+/// the encoder verifies the canonical ordering and name rules.+pub fn encode(entries: list[ref TreeEntry]) result[bytes.Bytes, derr.DecodeError] = {+ val b: mut buf.Buf = buf.new(@len(entries) * 48 + 8)+ buf.Buf.put_varint(b, @len(entries) as u64)+ val prev: mut bytes.Bytes = bytes.empty()+ val have_prev: mut bool = false+ val i: mut usize = 0+ for i < @len(entries) {+ val e = entry_at(entries, i)+ if !names.valid_name(e.name) {+ buf.Buf.free(b)+ return err derr.fail(derr.ErrorKind.InvalidName, i)+ }+ if have_prev && bytes.Bytes.cmp(prev, e.name) >= 0 {+ buf.Buf.free(b)+ return err derr.fail(derr.ErrorKind.Unsorted, i)+ }+ if !valid_kind(e.kind) {+ buf.Buf.free(b)+ return err derr.fail(derr.ErrorKind.InvalidValue, i)+ }+ buf.Buf.put_length_prefixed(b, e.name)+ buf.Buf.put_u8(b, e.kind)+ buf.Buf.put_id(b, e.target.ptr)+ prev = e.name+ have_prev = true+ i = i + 1+ }+ val out: bytes.Bytes = bytes.Bytes.dup(buf.Buf.view(b))+ buf.Buf.free(b)+ return ok out+}++pub fn free_tree(t: ref Tree) void = {+ for e in t.entries {+ val p: mut ref void = e as ref void+ trust @free(p)+ }+ @listfree(t.entries)+ val p2: mut ref void = t as ref void+ trust @free(p2)+}--- /dev/null+++ b/src/src/object/types.sx@@ -0,0 +1,40 @@+/// Object type tags and their human-readable names.++val str = use("std/string")++pub val CHUNK: u8 = 1+pub val BLOB: u8 = 2+pub val TREE: u8 = 3+pub val COMMIT: u8 = 4+pub val CONFLICT: u8 = 5+pub val OPERATION: u8 = 6+pub val VIEW: u8 = 7++pub fn name(t: u8) str.StringView = {+ if t == CHUNK {+ return "chunk"+ }+ if t == BLOB {+ return "blob"+ }+ if t == TREE {+ return "tree"+ }+ if t == COMMIT {+ return "commit"+ }+ if t == CONFLICT {+ return "conflict"+ }+ if t == OPERATION {+ return "operation"+ }+ if t == VIEW {+ return "view"+ }+ return "unknown"+}++pub fn is_valid(t: u8) bool = {+ return t >= CHUNK && t <= VIEW+}--- /dev/null+++ b/src/src/object/view.sx@@ -0,0 +1,398 @@+/// View objects: the user-visible state recorded by an operation.++val bytes = use("../core/bytes.sx")+val buf = use("../core/buf.sx")+val reader = use("../core/reader.sx")+val derr = use("../core/error.sx")+val prim = use("../core/primitives.sx")+val lists = use("../core/lists.sx")+val objid = use("id.sx")++pub type TargetSet = {+ adds: mut list[objid.Id]+ removes: mut list[objid.Id]+}++pub type Bookmark = {+ name: mut bytes.Bytes+ targets: mut TargetSet+}++pub type TagRef = {+ name: mut bytes.Bytes+ target: mut objid.Id+}++pub type RemoteRef = {+ remote: mut bytes.Bytes+ name: mut bytes.Bytes+ target: mut objid.Id+}++pub type WorkspaceRef = {+ workspace: mut bytes.Bytes+ target: mut objid.Id+}++pub type View = {+ heads: mut list[objid.Id]+ bookmarks: mut list[ref Bookmark]+ tags: mut list[ref TagRef]+ remote_refs: mut list[ref RemoteRef]+ working_copies: mut list[ref WorkspaceRef]+}++pub fn empty_target_set() TargetSet = {+ return TargetSet{adds: lists.new[objid.Id](), removes: lists.new[objid.Id]()}+}++fn id_at(ids: list[objid.Id], i: usize) objid.Id = {+ val o = @get(ids, i)+ if o is some v {+ return v+ }+ assert false+ return objid.id_none()+}++fn name_valid(b: bytes.Bytes) bool = {+ if b.len == 0 || b.len > prim.MAX_NAME_LEN {+ return false+ }+ val i: mut usize = 0+ for i < b.len {+ if bytes.Bytes.at(b, i) == 0 {+ return false+ }+ i = i + 1+ }+ return true+}++fn read_heads(r: mut reader.Reader) result[list[objid.Id], derr.DecodeError] = {+ val n: usize = reader.Reader.read_list_len(r, 1000000)?+ val out: mut list[objid.Id] = lists.new[objid.Id]()+ val prev: mut objid.Id = objid.id_none()+ val have_prev: mut bool = false+ val i: mut usize = 0+ for i < n {+ val at: usize = reader.Reader.offset(r)+ val p: ref u8 = reader.Reader.read_id(r)?+ val cur: objid.Id = objid.id(p)+ if have_prev {+ val c: i64 = objid.Id.cmp(prev, cur)+ if c == 0 {+ return err derr.fail(derr.ErrorKind.Duplicate, at)+ }+ if c > 0 {+ return err derr.fail(derr.ErrorKind.Unsorted, at)+ }+ }+ @append(out, cur)+ prev = cur+ have_prev = true+ i = i + 1+ }+ return ok out+}++fn read_id_list(+ r: mut reader.Reader,+ max: usize,+ optional: bool+) result[list[objid.Id], derr.DecodeError] = {+ val n: usize = reader.Reader.read_list_len(r, max)?+ val out: mut list[objid.Id] = lists.new[objid.Id]()+ val i: mut usize = 0+ for i < n {+ if optional {+ val p: ref u8 = reader.Reader.read_opt_id(r)?+ @append(out, objid.id(p))+ } else {+ val p2: ref u8 = reader.Reader.read_id(r)?+ @append(out, objid.id(p2))+ }+ i = i + 1+ }+ return ok out+}++fn contains_id(ids: list[objid.Id], v: objid.Id) bool = {+ for x in ids {+ if objid.Id.eql(x, v) {+ return true+ }+ }+ return false+}++fn all_same(ids: list[objid.Id]) bool = {+ if @len(ids) <= 1 {+ return true+ }+ val first = id_at(ids, 0)+ for x in ids {+ if !objid.Id.eql(first, x) {+ return false+ }+ }+ return true+}++fn read_target_set(r: mut reader.Reader) result[TargetSet, derr.DecodeError] = {+ val at: usize = reader.Reader.offset(r)+ val ts: mut TargetSet = empty_target_set()+ ts.adds = read_id_list(r, 64, true)?+ ts.removes = read_id_list(r, 64, true)?+ if @len(ts.adds) == 0 {+ return err derr.fail(derr.ErrorKind.InvalidValue, at)+ }+ if @len(ts.adds) != @len(ts.removes) + 1 {+ return err derr.fail(derr.ErrorKind.InvalidValue, at)+ }+ if @len(ts.adds) + @len(ts.removes) > prim.MAX_CONFLICT_TERMS {+ return err derr.fail(derr.ErrorKind.LimitExceeded, at)+ }+ for a in ts.adds {+ if contains_id(ts.removes, a) {+ return err derr.fail(derr.ErrorKind.InvalidValue, at)+ }+ }+ if all_same(ts.adds) && @len(ts.adds) > 1 {+ return err derr.fail(derr.ErrorKind.InvalidValue, at)+ }+ return ok ts+}++fn read_bookmarks(r: mut reader.Reader) result[list[ref Bookmark], derr.DecodeError] = {+ val n: usize = reader.Reader.read_list_len(r, 1000000)?+ val out: mut list[ref Bookmark] = lists.new[ref Bookmark]()+ val prev: mut bytes.Bytes = bytes.empty()+ val have_prev: mut bool = false+ val i: mut usize = 0+ for i < n {+ val at: usize = reader.Reader.offset(r)+ val name: bytes.Bytes = reader.Reader.read_bytes(r, prim.MAX_NAME_LEN)?+ if !name_valid(name) {+ return err derr.fail(derr.ErrorKind.InvalidName, at)+ }+ if have_prev {+ val c: i64 = bytes.Bytes.cmp(prev, name)+ if c == 0 {+ return err derr.fail(derr.ErrorKind.Duplicate, at)+ }+ if c > 0 {+ return err derr.fail(derr.ErrorKind.Unsorted, at)+ }+ }+ val ts: TargetSet = read_target_set(r)?+ val bm: mut ref Bookmark = @alloc(@sizeof(Bookmark)) as ref Bookmark+ bm.name = name+ bm.targets = ts+ @append(out, bm)+ prev = name+ have_prev = true+ i = i + 1+ }+ return ok out+}++fn read_tags(r: mut reader.Reader) result[list[ref TagRef], derr.DecodeError] = {+ val n: usize = reader.Reader.read_list_len(r, 1000000)?+ val out: mut list[ref TagRef] = lists.new[ref TagRef]()+ val prev: mut bytes.Bytes = bytes.empty()+ val have_prev: mut bool = false+ val i: mut usize = 0+ for i < n {+ val at: usize = reader.Reader.offset(r)+ val name: bytes.Bytes = reader.Reader.read_bytes(r, prim.MAX_NAME_LEN)?+ if !name_valid(name) {+ return err derr.fail(derr.ErrorKind.InvalidName, at)+ }+ if have_prev {+ val c: i64 = bytes.Bytes.cmp(prev, name)+ if c == 0 {+ return err derr.fail(derr.ErrorKind.Duplicate, at)+ }+ if c > 0 {+ return err derr.fail(derr.ErrorKind.Unsorted, at)+ }+ }+ val target: ref u8 = reader.Reader.read_id(r)?+ val t: mut ref TagRef = @alloc(@sizeof(TagRef)) as ref TagRef+ t.name = name+ t.target = objid.id(target)+ @append(out, t)+ prev = name+ have_prev = true+ i = i + 1+ }+ return ok out+}++fn ref_cmp(remote_a: bytes.Bytes, name_a: bytes.Bytes, remote_b: bytes.Bytes, name_b: bytes.Bytes) i64 = {+ val c: i64 = bytes.Bytes.cmp(remote_a, remote_b)+ if c != 0 {+ return c+ }+ return bytes.Bytes.cmp(name_a, name_b)+}++fn read_remote_refs(r: mut reader.Reader) result[list[ref RemoteRef], derr.DecodeError] = {+ val n: usize = reader.Reader.read_list_len(r, 1000000)?+ val out: mut list[ref RemoteRef] = lists.new[ref RemoteRef]()+ val prev_remote: mut bytes.Bytes = bytes.empty()+ val prev_name: mut bytes.Bytes = bytes.empty()+ val have_prev: mut bool = false+ val i: mut usize = 0+ for i < n {+ val at: usize = reader.Reader.offset(r)+ val remote: bytes.Bytes = reader.Reader.read_bytes(r, prim.MAX_NAME_LEN)?+ val name: bytes.Bytes = reader.Reader.read_bytes(r, prim.MAX_NAME_LEN)?+ if !name_valid(remote) || !name_valid(name) {+ return err derr.fail(derr.ErrorKind.InvalidName, at)+ }+ if have_prev {+ val c: i64 = ref_cmp(prev_remote, prev_name, remote, name)+ if c == 0 {+ return err derr.fail(derr.ErrorKind.Duplicate, at)+ }+ if c > 0 {+ return err derr.fail(derr.ErrorKind.Unsorted, at)+ }+ }+ val target: ref u8 = reader.Reader.read_id(r)?+ val rr: mut ref RemoteRef = @alloc(@sizeof(RemoteRef)) as ref RemoteRef+ rr.remote = remote+ rr.name = name+ rr.target = objid.id(target)+ @append(out, rr)+ prev_remote = remote+ prev_name = name+ have_prev = true+ i = i + 1+ }+ return ok out+}++fn read_working_copies(r: mut reader.Reader) result[list[ref WorkspaceRef], derr.DecodeError] = {+ val n: usize = reader.Reader.read_list_len(r, 1000000)?+ val out: mut list[ref WorkspaceRef] = lists.new[ref WorkspaceRef]()+ val prev: mut bytes.Bytes = bytes.empty()+ val have_prev: mut bool = false+ val i: mut usize = 0+ for i < n {+ val at: usize = reader.Reader.offset(r)+ val workspace: bytes.Bytes = reader.Reader.read_bytes(r, prim.MAX_NAME_LEN)?+ if !name_valid(workspace) {+ return err derr.fail(derr.ErrorKind.InvalidName, at)+ }+ if have_prev {+ val c: i64 = bytes.Bytes.cmp(prev, workspace)+ if c == 0 {+ return err derr.fail(derr.ErrorKind.Duplicate, at)+ }+ if c > 0 {+ return err derr.fail(derr.ErrorKind.Unsorted, at)+ }+ }+ val target: ref u8 = reader.Reader.read_id(r)?+ val w: mut ref WorkspaceRef = @alloc(@sizeof(WorkspaceRef)) as ref WorkspaceRef+ w.workspace = workspace+ w.target = objid.id(target)+ @append(out, w)+ prev = workspace+ have_prev = true+ i = i + 1+ }+ return ok out+}++pub fn decode(body: bytes.Bytes) result[ref View, derr.DecodeError] = {+ val r: mut reader.Reader = reader.new(body.ptr, body.len)+ val v: mut ref View = @alloc(@sizeof(View)) as ref View+ v.heads = read_heads(r)?+ v.bookmarks = read_bookmarks(r)?+ v.tags = read_tags(r)?+ v.remote_refs = read_remote_refs(r)?+ v.working_copies = read_working_copies(r)?+ reader.Reader.finish(r)?+ return ok v+}++fn put_target_set(b: mut buf.Buf, ts: TargetSet) void = {+ buf.Buf.put_varint(b, @len(ts.adds) as u64)+ for x in ts.adds {+ buf.Buf.put_opt_id(b, x.ptr)+ }+ buf.Buf.put_varint(b, @len(ts.removes) as u64)+ for x in ts.removes {+ buf.Buf.put_opt_id(b, x.ptr)+ }+}++pub fn encode(v: ref View) bytes.Bytes = {+ val b: mut buf.Buf = buf.new(256)+ buf.Buf.put_varint(b, @len(v.heads) as u64)+ val i: mut usize = 0+ for i < @len(v.heads) {+ buf.Buf.put_id(b, id_at(v.heads, i).ptr)+ i = i + 1+ }+ buf.Buf.put_varint(b, @len(v.bookmarks) as u64)+ for bm in v.bookmarks {+ buf.Buf.put_length_prefixed(b, bm.name)+ put_target_set(b, bm.targets)+ }+ buf.Buf.put_varint(b, @len(v.tags) as u64)+ for t in v.tags {+ buf.Buf.put_length_prefixed(b, t.name)+ buf.Buf.put_id(b, t.target.ptr)+ }+ buf.Buf.put_varint(b, @len(v.remote_refs) as u64)+ for rr in v.remote_refs {+ buf.Buf.put_length_prefixed(b, rr.remote)+ buf.Buf.put_length_prefixed(b, rr.name)+ buf.Buf.put_id(b, rr.target.ptr)+ }+ buf.Buf.put_varint(b, @len(v.working_copies) as u64)+ for w in v.working_copies {+ buf.Buf.put_length_prefixed(b, w.workspace)+ buf.Buf.put_id(b, w.target.ptr)+ }+ val out: bytes.Bytes = bytes.Bytes.dup(buf.Buf.view(b))+ buf.Buf.free(b)+ return out+}++fn free_target_set(ts: TargetSet) void = {+ @listfree(ts.adds)+ @listfree(ts.removes)+}++pub fn free_view(v: ref View) void = {+ @listfree(v.heads)+ for bm in v.bookmarks {+ free_target_set(bm.targets)+ val p: mut ref void = bm as ref void+ trust @free(p)+ }+ @listfree(v.bookmarks)+ for t in v.tags {+ val p: mut ref void = t as ref void+ trust @free(p)+ }+ @listfree(v.tags)+ for rr in v.remote_refs {+ val p: mut ref void = rr as ref void+ trust @free(p)+ }+ @listfree(v.remote_refs)+ for w in v.working_copies {+ val p: mut ref void = w as ref void+ trust @free(p)+ }+ @listfree(v.working_copies)+ val p2: mut ref void = v as ref void+ trust @free(p2)+}--- /dev/null+++ b/src/src/store/fsck.sx@@ -0,0 +1,626 @@+/// `vn fsck`: canonical-form, hash, referential-integrity, and op-log checks.++val str = use("std/string")+val stdio = use("std/stdio")+val bytes = use("../core/bytes.sx")+val lists = use("../core/lists.sx")+val derr = use("../core/error.sx")+val prim = use("../core/primitives.sx")+val objid = use("../object/id.sx")+val types = use("../object/types.sx")+val blob = use("../object/blob.sx")+val tree = use("../object/tree.sx")+val conflict = use("../object/conflict.sx")+val commit = use("../object/commit.sx")+val operation = use("../object/operation.sx")+val view = use("../object/view.sx")+val pack = use("pack.sx")+val index = use("index.sx")+val store = use("store.sx")+val layout = use("layout.sx")+val files = use("../io/files.sx")++pub type Ctx = {+ repo: layout.Repo+ promisor: mut bool+ verbose: mut bool+ errors: mut usize+ warnings: mut usize+}++fn report(ctx: mut Ctx, path: str.StringView, msg: str.StringView) void = {+ ctx.errors = ctx.errors + 1+ trust stdio.eprint("fsck: {s}: {s}\n", {path, msg})+}++fn report_id(ctx: mut Ctx, path: str.StringView, msg: str.StringView, id: objid.Id) void = {+ ctx.errors = ctx.errors + 1+ val hx: ref u8 = objid.Id.hex(id)+ trust stdio.eprint("fsck: {s}: {s} {s}\n", {path, msg, str.from_cstr(hx)})+ val p: mut ref void = hx as ref void+ trust @free(p)+}++fn warn(ctx: mut Ctx, path: str.StringView, msg: str.StringView) void = {+ ctx.warnings = ctx.warnings + 1+ if ctx.verbose {+ trust stdio.eprint("fsck: warning: {s}: {s}\n", {path, msg})+ }+}++fn format_ok(d: bytes.Bytes) bool = {+ val expected: bytes.Bytes = bytes.bytes(c"vein-store 1", 12)+ if bytes.Bytes.eql(d, expected) {+ return true+ }+ if d.len == 13 && bytes.Bytes.eql(bytes.Bytes.slice(d, 0, 12), expected) {+ return bytes.Bytes.at(d, 12) == 10+ }+ return false+}++fn check_format(ctx: mut Ctx) bool = trust {+ val p: str.StringView = layout.format_path(ctx.repo)+ val data = files.read_all(p)+ files.free_path(p)+ val d: mut bytes.Bytes = bytes.empty()+ match data {+ some x => {+ d = x+ }+ none => {+ report(ctx, layout.root_view(ctx.repo), "missing .vein/format")+ return false+ }+ }+ val valid_format: bool = format_ok(d)+ files.free_buffer(d)+ if !valid_format {+ report(ctx, layout.root_view(ctx.repo), "unsupported .vein/format")+ return false+ }+ return true+}++fn expected_type(value_kind: u8) u8 = {+ if value_kind == 1 || value_kind == 2 || value_kind == 3 {+ return types.BLOB+ }+ if value_kind == 4 {+ return types.TREE+ }+ if value_kind == 6 {+ return types.CONFLICT+ }+ return 0+}++fn check_ref(+ ctx: mut Ctx,+ handles: list[ref store.Handle],+ path: str.StringView,+ id: objid.Id,+ expected: u8,+ what: str.StringView+) bool = trust {+ if objid.Id.is_none(id) {+ report(ctx, path, "absent reference where a value is required")+ return false+ }+ val loc: mut store.Loc = store.Loc{pack_index: 0, record_index: 0, kind: 0}+ val found: bool = store.find_handles(handles, id, loc)+ if !found {+ val promised: bool = ctx.promisor && (expected == types.CHUNK || expected == types.BLOB)+ if promised {+ warn(ctx, path, "missing promised object")+ }+ if !promised {+ val msg: ref u8 = @fmtalloc("missing {s} object", {what})+ report_id(ctx, path, str.from_cstr(msg), id)+ val mp: mut ref void = msg as ref void+ @free(mp)+ }+ return promised+ }+ if loc.kind != expected {+ val msg2: ref u8 = @fmtalloc(+ "object has type {s}, expected {s}",+ {types.name(loc.kind), types.name(expected)}+ )+ report_id(ctx, path, str.from_cstr(msg2), id)+ val mp2: mut ref void = msg2 as ref void+ @free(mp2)+ return false+ }+ return true+}++fn check_blob(ctx: mut Ctx, handles: list[ref store.Handle], path: str.StringView, b: ref blob.Blob) void = trust {+ if b.form == blob.FORM_INLINE {+ return+ }+ val expected: mut u8 = types.BLOB+ if b.form == blob.FORM_LEAF {+ expected = types.CHUNK+ }+ for e in b.entries {+ val _ = check_ref(ctx, handles, path, e.id, expected, "blob")+ }+}++fn check_tree(ctx: mut Ctx, handles: list[ref store.Handle], path: str.StringView, t: ref tree.Tree) void = trust {+ for e in t.entries {+ val expected: mut u8 = 0+ if e.kind == tree.KIND_FILE || e.kind == tree.KIND_EXECUTABLE || e.kind == tree.KIND_SYMLINK {+ expected = types.BLOB+ }+ if e.kind == tree.KIND_SUBTREE {+ expected = types.TREE+ }+ if e.kind == tree.KIND_CONFLICT {+ expected = types.CONFLICT+ }+ if expected != 0 {+ val _ = check_ref(ctx, handles, path, e.target, expected, "tree")+ }+ }+}++fn check_conflict(ctx: mut Ctx, handles: list[ref store.Handle], path: str.StringView, c: ref conflict.Conflict) void = trust {+ for v in c.adds {+ val expected: u8 = expected_type(v.kind)+ if expected != 0 {+ val _ = check_ref(ctx, handles, path, v.target, expected, "conflict")+ }+ }+ for v in c.removes {+ val expected: u8 = expected_type(v.kind)+ if expected != 0 {+ val _ = check_ref(ctx, handles, path, v.target, expected, "conflict")+ }+ }+}++fn check_commit(ctx: mut Ctx, handles: list[ref store.Handle], path: str.StringView, c: ref commit.Commit) void = trust {+ for p in c.parents {+ val _ = check_ref(ctx, handles, path, p, types.COMMIT, "parent commit")+ }+ val _ = check_ref(ctx, handles, path, c.root_tree, types.TREE, "root tree")+}++fn check_operation(ctx: mut Ctx, handles: list[ref store.Handle], path: str.StringView, op: ref operation.Operation) void = trust {+ for p in op.parents {+ val _ = check_ref(ctx, handles, path, p, types.OPERATION, "parent operation")+ }+ val _ = check_ref(ctx, handles, path, op.view, types.VIEW, "view")+}++fn check_view(ctx: mut Ctx, handles: list[ref store.Handle], path: str.StringView, v: ref view.View) void = trust {+ for h in v.heads {+ val _ = check_ref(ctx, handles, path, h, types.COMMIT, "head commit")+ }+ for bm in v.bookmarks {+ for a in bm.targets.adds {+ if !objid.Id.is_none(a) {+ val _ = check_ref(ctx, handles, path, a, types.COMMIT, "bookmark")+ }+ }+ for r in bm.targets.removes {+ if !objid.Id.is_none(r) {+ val _ = check_ref(ctx, handles, path, r, types.COMMIT, "bookmark")+ }+ }+ }+ for t in v.tags {+ val _ = check_ref(ctx, handles, path, t.target, types.COMMIT, "tag")+ }+ for rr in v.remote_refs {+ val _ = check_ref(ctx, handles, path, rr.target, types.COMMIT, "remote ref")+ }+ for w in v.working_copies {+ val _ = check_ref(ctx, handles, path, w.target, types.COMMIT, "working copy")+ }+}++fn check_object(+ ctx: mut Ctx,+ handles: list[ref store.Handle],+ path: str.StringView,+ id: objid.Id,+ kind: u8,+ body: bytes.Bytes+) void = trust {+ val computed: objid.Id = objid.object_id(kind, body)+ val hash_ok: bool = objid.Id.eql(computed, id)+ val cp: mut ref void = computed.ptr as ref void+ @free(cp)+ if !hash_ok {+ report_id(ctx, path, "hash mismatch for", id)+ return+ }++ if kind == types.CHUNK {+ if body.len == 0 || body.len > prim.MAX_CHUNK_LEN {+ report_id(ctx, path, "invalid chunk length for", id)+ }+ return+ }+ if kind == types.BLOB {+ match blob.decode(body) {+ ok x => {+ check_blob(ctx, handles, path, x)+ blob.free_blob(x)+ }+ err e => {+ report_decode(ctx, path, "blob", e)+ }+ }+ return+ }+ if kind == types.TREE {+ match tree.decode(body) {+ ok x => {+ check_tree(ctx, handles, path, x)+ tree.free_tree(x)+ }+ err e => {+ report_decode(ctx, path, "tree", e)+ }+ }+ return+ }+ if kind == types.CONFLICT {+ match conflict.decode(body) {+ ok x => {+ check_conflict(ctx, handles, path, x)+ conflict.free_conflict(x)+ }+ err e => {+ report_decode(ctx, path, "conflict", e)+ }+ }+ return+ }+ if kind == types.COMMIT {+ match commit.decode(body) {+ ok x => {+ check_commit(ctx, handles, path, x)+ commit.free_commit(x)+ }+ err e => {+ report_decode(ctx, path, "commit", e)+ }+ }+ return+ }+ if kind == types.OPERATION {+ match operation.decode(body) {+ ok x => {+ check_operation(ctx, handles, path, x)+ operation.free_operation(x)+ }+ err e => {+ report_decode(ctx, path, "operation", e)+ }+ }+ return+ }+ if kind == types.VIEW {+ match view.decode(body) {+ ok x => {+ check_view(ctx, handles, path, x)+ view.free_view(x)+ }+ err e => {+ report_decode(ctx, path, "view", e)+ }+ }+ }+}++fn report_decode(ctx: mut Ctx, path: str.StringView, what: str.StringView, e: derr.DecodeError) void = {+ val msg: ref u8 = trust @fmtalloc("invalid {s} at byte {d}: {s}", {what, e.offset, derr.ErrorKind.name(e.kind)})+ report(ctx, path, str.from_cstr(msg))+ val p: mut ref void = msg as ref void+ trust @free(p)+}++/// Verify one pack/index pair and add the validated pair to the store.+fn load_pack(ctx: mut Ctx, handles: mut list[ref store.Handle], dir: str.StringView, name: str.StringView) void = trust {+ val pview: str.StringView = files.join(dir, name)+ val pdata_opt = files.read_all(pview)+ val pdata: mut bytes.Bytes = bytes.empty()+ match pdata_opt {+ some x => {+ pdata = x+ }+ none => {+ report(ctx, pview, "cannot read pack")+ files.free_path(pview)+ return+ }+ }+ val pr = pack.decode(pdata)+ val p: mut ref pack.Pack = none+ match pr {+ ok x => {+ p = x+ }+ err e => {+ report_decode(ctx, pview, "pack", e)+ files.free_buffer(pdata)+ files.free_path(pview)+ return+ }+ }++ if name.len <= 6 {+ report(ctx, pview, "malformed pack file name")+ pack.free_pack(p)+ files.free_path(pview)+ return+ }+ val base: str.StringView = str.view(name.ptr, name.len - 6)+ val iname: str.StringView = files.with_suffix(base, ".vidx")+ val iview: str.StringView = files.join(dir, iname)+ files.free_path(iname)+ val idata_opt = files.read_all(iview)+ val idata: mut bytes.Bytes = bytes.empty()+ match idata_opt {+ some x => {+ idata = x+ }+ none => {+ report(ctx, pview, "pack has no index")+ pack.free_pack(p)+ files.free_path(pview)+ files.free_path(iview)+ return+ }+ }+ val ir = index.decode(idata, p.trailer)+ val idx: mut ref index.Index = none+ match ir {+ ok x => {+ idx = x+ }+ err e => {+ report_decode(ctx, iview, "index", e)+ files.free_buffer(idata)+ pack.free_pack(p)+ files.free_path(pview)+ files.free_path(iview)+ return+ }+ }+ files.free_path(iview)++ val eligible: mut bool = true+ if idx.count != p.count {+ report(ctx, pview, "pack and index object counts differ")+ eligible = false+ }+ if eligible {+ val visited: ref u8 = @alloc(p.count + 1) as ref u8+ @memset(visited as ref void, 0, p.count + 1)+ val j: mut usize = 0+ for j < idx.count {+ val iid: objid.Id = index.Index.id_at(idx, j)+ val off: u64 = index.Index.offset_at(idx, j)+ match pack.Pack.find_by_offset(p, off) {+ some r => {+ if !objid.Id.eql(pack.Pack.id_at(p, r), iid) {+ report_id(ctx, pview, "index id does not match record for", iid)+ eligible = false+ }+ if @load8(@ptradd(visited, r as i64)) != 0 {+ report_id(ctx, pview, "record indexed more than once", iid)+ eligible = false+ }+ @store8(@ptradd(visited, r as i64), 1)+ }+ none => {+ report_id(ctx, pview, "index offset names no record for", iid)+ }+ }+ j = j + 1+ }+ val k: mut usize = 0+ for k < p.count {+ if @load8(@ptradd(visited, k as i64)) == 0 {+ report_id(ctx, pview, "record is not indexed", pack.Pack.id_at(p, k))+ eligible = false+ }+ k = k + 1+ }+ @free(visited as ref void)+ }++ if eligible {+ store.add_handle(handles, pview, p, idx)+ } else {+ index.free_index(idx)+ pack.free_pack(p)+ files.free_path(pview)+ }+}++fn scan_packs(ctx: mut Ctx, handles: mut list[ref store.Handle]) void = trust {+ val dir: str.StringView = layout.packs_dir(ctx.repo)+ if !files.exists_dir(dir) {+ report(ctx, dir, "missing store/packs directory")+ files.free_path(dir)+ return+ }+ val names: list[ref u8] = files.list_dir(dir)+ for n in names {+ val nv: str.StringView = str.from_cstr(n)+ if files.name_ends_with(n, c".vidx") {+ val pack_name: str.StringView = str.view(nv.ptr, nv.len - 5)+ val pn: str.StringView = files.with_suffix(pack_name, ".vpack")+ val ppath: str.StringView = files.join(dir, pn)+ if !files.exists_file(ppath) {+ report(ctx, ppath, "index has no pack")+ }+ files.free_path(ppath)+ files.free_path(pn)+ }+ }+ for n in names {+ val nv2: str.StringView = str.from_cstr(n)+ if files.name_ends_with(n, c".vpack") {+ load_pack(ctx, handles, dir, nv2)+ }+ }+ files.free_names(names)+ files.free_path(dir)+}++/// Verify every object body in the loaded packs.+fn verify_objects(ctx: mut Ctx, handles: list[ref store.Handle]) void = trust {+ val i: mut usize = 0+ for i < @len(handles) {+ val h = store.handle_list_at(handles, i)+ val j: mut usize = 0+ for j < h.pack.count {+ match pack.get(h.pack, j) {+ ok body => {+ check_object(ctx, handles, h.path, pack.Pack.id_at(h.pack, j), pack.Pack.kind_at(h.pack, j), body)+ val bp: mut ref void = body.ptr as ref void+ if body.ptr != none {+ @free(bp)+ }+ }+ err e => {+ report_decode(ctx, h.path, "record", e)+ }+ }+ j = j + 1+ }+ i = i + 1+ }+}++fn seen_contains(seen: list[objid.Id], id: objid.Id) bool = {+ for x in seen {+ if objid.Id.eql(x, id) {+ return true+ }+ }+ return false+}++fn load_op(+ ctx: mut Ctx,+ handles: list[ref store.Handle],+ path: str.StringView,+ id: objid.Id,+ seen: mut list[objid.Id],+ frontier: mut list[objid.Id]+) void = trust {+ if seen_contains(seen, id) {+ return+ }+ @append(seen, id)+ val loc: mut store.Loc = store.Loc{pack_index: 0, record_index: 0, kind: 0}+ if !store.find_handles(handles, id, loc) {+ report_id(ctx, path, "operation head or parent is missing:", id)+ return+ }+ if loc.kind != types.OPERATION {+ report_id(ctx, path, "op-log entry is not an operation:", id)+ return+ }+ val bodyr = store.get_handles(handles, loc)+ val body: mut bytes.Bytes = bytes.empty()+ match bodyr {+ ok x => {+ body = x+ }+ err e => {+ report_decode(ctx, path, "operation", e)+ return+ }+ }+ match operation.decode(body) {+ ok o => {+ for p in o.parents {+ @append(frontier, p)+ }+ val _ = check_ref(ctx, handles, path, o.view, types.VIEW, "operation view")+ operation.free_operation(o)+ }+ err e => {+ report_decode(ctx, path, "operation", e)+ }+ }+ val bp: mut ref void = body.ptr as ref void+ if body.ptr != none {+ @free(bp)+ }+}++fn check_op_log(ctx: mut Ctx, handles: list[ref store.Handle]) void = trust {+ val dir: str.StringView = layout.op_heads_dir(ctx.repo)+ if !files.exists_dir(dir) {+ report(ctx, dir, "missing op_heads directory")+ files.free_path(dir)+ return+ }+ val names: list[ref u8] = files.list_dir(dir)+ val frontier: mut list[objid.Id] = lists.new[objid.Id]()+ for n in names {+ val nv: str.StringView = str.from_cstr(n)+ if nv.len != 64 {+ report(ctx, dir, "op_heads entry is not a 64-character id")+ continue+ }+ val raw_id: ref u8 = @alloc(32) as ref u8+ val parsed: bool = objid.hex_decode(n, 32, raw_id)+ if !parsed {+ report(ctx, dir, "op_heads entry is not hexadecimal")+ @free(raw_id as ref void)+ continue+ }+ @append(frontier, objid.id(raw_id))+ }+ val seen: mut list[objid.Id] = lists.new[objid.Id]()+ for @len(frontier) > 0 {+ val last: usize = @len(frontier) - 1+ val id: objid.Id = @remove(frontier, last)+ load_op(ctx, handles, dir, id, seen, frontier)+ }+ @listfree(seen)+ @listfree(frontier)+ files.free_names(names)+ files.free_path(dir)+}++/// Run all M0 structural checks. Returns a process exit status.+pub fn check(repo: layout.Repo, verbose: bool) i32 = trust {+ val handles: mut list[ref store.Handle] = lists.new[ref store.Handle]()+ val ctx: mut Ctx = Ctx{+ repo: repo,+ promisor: false,+ verbose: verbose,+ errors: 0,+ warnings: 0+ }+ val format_valid: bool = check_format(ctx)+ if format_valid {+ ctx.promisor = store.has_promisor(repo)+ scan_packs(ctx, handles)+ verify_objects(ctx, handles)+ check_op_log(ctx, handles)+ }+ store.close_handles(handles)+ if ctx.warnings > 0 && verbose {+ stdio.eprint("fsck: {d} warning(s)\n", {ctx.warnings})+ }+ if ctx.errors == 0 {+ stdio.eprint("fsck: clean\n", {})+ return 0+ }+ stdio.eprint("fsck: {d} error(s)\n", {ctx.errors})+ return 1+}--- /dev/null+++ b/src/src/store/index.sx@@ -0,0 +1,219 @@+/// Pack index files (`vidx`).++val bytes = use("../core/bytes.sx")+val buf = use("../core/buf.sx")+val reader = use("../core/reader.sx")+val derr = use("../core/error.sx")+val objid = use("../object/id.sx")+val records = use("records.sx")+val b3 = use("../crypto/blake3.sx")+val files = use("../io/files.sx")++pub val INDEX_FORMAT_VERSION: u32 = 1++pub type Index = {+ data: mut bytes.Bytes+ count: mut usize+ ids: mut ref u8+ offsets: mut ref u8+ pack_trailer: mut bytes.Bytes+}++pub fn (Index) id_at(idx: self, i: usize) objid.Id = {+ pre {+ in_bounds: i < idx.count+ }+ return objid.id(trust @ptradd(idx.ids, (i * 32) as i64))+}++pub fn (Index) offset_at(idx: self, i: usize) u64 = {+ pre {+ in_bounds: i < idx.count+ }+ return trust @load64(@ptradd(idx.offsets, (i * 8) as i64)) as u64+}++fn compare_id(a: ref u8, b: ref u8) i64 = {+ return bytes.Bytes.cmp(bytes.bytes(a, 32), bytes.bytes(b, 32))+}++/// Binary search in the sorted ID array.+pub fn (Index) find(idx: self, id: objid.Id) option[usize] = {+ pre {+ present: id.ptr != none+ }+ val lo: mut usize = 0+ val hi: mut usize = idx.count+ for lo < hi {+ val mid: usize = lo + (hi - lo) / 2+ val cur: ref u8 = trust @ptradd(idx.ids, (mid * 32) as i64)+ val c: i64 = compare_id(cur, id.ptr)+ if c == 0 {+ return some mid+ }+ if c < 0 {+ lo = mid + 1+ } else {+ hi = mid+ }+ }+ return none+}++pub fn free_index(idx: ref Index) void = {+ files.free_buffer(idx.data)+ val p: mut ref void = idx as ref void+ trust @free(p)+}++pub fn decode(+ data: bytes.Bytes,+ expected_pack_trailer: bytes.Bytes+) result[ref Index, derr.DecodeError] = {+ if data.len < 1032 + 64 {+ return err derr.fail(derr.ErrorKind.UnexpectedEnd, 0)+ }+ val r: mut reader.Reader = reader.new(data.ptr, data.len)+ val magic: bytes.Bytes = reader.Reader.read_raw(r, 4)?+ if !bytes.Bytes.eql(magic, bytes.bytes(c"VIX1", 4)) {+ return err derr.fail(derr.ErrorKind.InvalidMagic, 0)+ }+ val version: u32 = reader.Reader.read_u32_le(r)?+ if version != INDEX_FORMAT_VERSION {+ return err derr.fail(derr.ErrorKind.UnsupportedVersion, 4)+ }++ val prev: mut u32 = 0+ val last: mut u32 = 0+ val i: mut usize = 0+ for i < 256 {+ val v: u32 = reader.Reader.read_u32_le(r)?+ if v < prev {+ return err derr.fail(derr.ErrorKind.Unsorted, reader.Reader.offset(r) - 4)+ }+ prev = v+ last = v+ i = i + 1+ }++ val base: usize = 1032 + 64+ if data.len < base {+ return err derr.fail(derr.ErrorKind.UnexpectedEnd, 1032)+ }+ val body: usize = data.len - base+ if body % 40 != 0 {+ return err derr.fail(derr.ErrorKind.TrailingBytes, base)+ }+ val count: usize = body / 40+ if count != (last as usize) {+ return err derr.fail(derr.ErrorKind.Corrupt, 1032)+ }++ val ids: ref u8 = trust @ptradd(data.ptr, 1032 as i64)+ val offsets: ref u8 = trust @ptradd(ids, (count * 32) as i64)+ val pack_trailer: bytes.Bytes = bytes.Bytes.slice(+ data,+ 1032 + count * 32 + count * 8,+ 1032 + count * 32 + count * 8 + 32+ )+ val index_trailer_off: usize = data.len - 32++ val digest: ref u8 = @alloc(32) as ref u8+ trust b3.hash(data.ptr, index_trailer_off, digest)+ val valid: bool = bytes.Bytes.eql(bytes.bytes(digest, 32), bytes.Bytes.slice(data, index_trailer_off, data.len))+ trust @free(digest as ref void)+ if !valid {+ return err derr.fail(derr.ErrorKind.HashMismatch, index_trailer_off)+ }+ if expected_pack_trailer.ptr != none && !bytes.Bytes.eql(pack_trailer, expected_pack_trailer) {+ return err derr.fail(derr.ErrorKind.Corrupt, index_trailer_off)+ }++ val counts: ref u32 = @alloc(1024) as ref u32+ trust @memset(counts as ref void, 0, 1024)+ val j: mut usize = 0+ for j < count {+ val cur: ref u8 = trust @ptradd(ids, (j * 32) as i64)+ if j > 0 {+ val prev_id: ref u8 = trust @ptradd(ids, ((j - 1) * 32) as i64)+ val c: i64 = compare_id(prev_id, cur)+ if c == 0 {+ trust @free(counts as ref void)+ return err derr.fail(derr.ErrorKind.Duplicate, 1032 + j * 32)+ }+ if c > 0 {+ trust @free(counts as ref void)+ return err derr.fail(derr.ErrorKind.Unsorted, 1032 + j * 32)+ }+ }+ val first: u8 = trust @load8(cur)+ val slot: ref u32 = trust @ptradd(counts as ref void, (first as i64) * 4) as ref u32+ val c0: u32 = @load32(slot) as u32+ @store32(slot, (c0 + 1) as i32)+ j = j + 1+ }+ val running: mut u32 = 0+ val k: mut usize = 0+ for k < 256 {+ val slot2: ref u32 = trust @ptradd(counts as ref void, (k as i64) * 4) as ref u32+ running = running + (@load32(slot2) as u32)+ val stored: u32 = trust (@load32(@ptradd(data.ptr, (8 + k * 4) as i64)) as u32)+ if stored != running {+ trust @free(counts as ref void)+ return err derr.fail(derr.ErrorKind.Corrupt, 8 + k * 4)+ }+ k = k + 1+ }+ trust @free(counts as ref void)++ val idx: mut ref Index = @alloc(@sizeof(Index)) as ref Index+ idx.data = data+ idx.count = count+ idx.ids = ids+ idx.offsets = offsets+ idx.pack_trailer = pack_trailer+ return ok idx+}++pub fn encode(recs: list[ref records.RecordMeta], pack_trailer: bytes.Bytes) bytes.Bytes = {+ pre {+ trailer_len: pack_trailer.len == 32+ }+ val counts: ref u32 = @alloc(1024) as ref u32+ trust @memset(counts as ref void, 0, 1024)+ for r in recs {+ val first: u8 = trust @load8(r.id.ptr)+ val slot: ref u32 = trust @ptradd(counts as ref void, (first as i64) * 4) as ref u32+ val c0: u32 = @load32(slot) as u32+ @store32(slot, (c0 + 1) as i32)+ }++ val b: mut buf.Buf = buf.new(@len(recs) * 40 + 128)+ buf.Buf.put_raw(b, c"VIX1", 4)+ buf.Buf.put_u32_le(b, INDEX_FORMAT_VERSION)+ val running: mut u32 = 0+ val k: mut usize = 0+ for k < 256 {+ val slot2: ref u32 = trust @ptradd(counts as ref void, (k as i64) * 4) as ref u32+ running = running + (@load32(slot2) as u32)+ buf.Buf.put_u32_le(b, running)+ k = k + 1+ }+ for r in recs {+ buf.Buf.put_id(b, r.id.ptr)+ }+ for r in recs {+ buf.Buf.put_u64_le(b, r.offset)+ }+ buf.Buf.put_raw(b, pack_trailer.ptr, 32)++ val digest: ref u8 = @alloc(32) as ref u8+ trust b3.hash(b.ptr, b.len, digest)+ buf.Buf.put_raw(b, digest, 32)+ trust @free(digest as ref void)+ trust @free(counts as ref void)++ val out: bytes.Bytes = bytes.Bytes.dup(buf.Buf.view(b))+ buf.Buf.free(b)+ return out+}--- /dev/null+++ b/src/src/store/layout.sx@@ -0,0 +1,186 @@+/// Repository layout and discovery.++val str = use("std/string")+val path = use("std/path")+val fs = use("std/fs")+val bytes = use("../core/bytes.sx")+val files = use("../io/files.sx")++pub val FORMAT_TEXT_LEN: usize = 12++fn format_text() bytes.Bytes = {+ return bytes.bytes(c"vein-store 1", 12)+}++pub type Repo = {+ root: bytes.Bytes+}++pub fn root_view(r: Repo) str.StringView = {+ return str.view(r.root.ptr, r.root.len as i64)+}++pub fn free_repo(r: Repo) void = {+ files.free_buffer(r.root)+}++fn canonical(p: str.StringView) ref u8 = {+ return trust path.canonicalize_path(p)+}++/// Find the nearest ancestor (or `start` itself) containing `.vein/format`.+pub fn discover(start: str.StringView) option[Repo] = {+ val abs: mut str.StringView = start+ val joined: mut str.StringView = str.view(none, 0)+ val absolute: bool = start.len > 0 && trust @load8(start.ptr) == 47+ if !absolute {+ val cwd = trust fs.cwd_cstr()+ if cwd is some c {+ joined = files.join(str.from_cstr(c), start)+ abs = joined+ val cp: mut ref void = c as ref void+ trust @free(cp)+ }+ }+ val cpath: mut ref u8 = canonical(abs)+ if joined.ptr != none {+ files.free_path(joined)+ }+ if cpath == none {+ return none+ }+ for {+ val root_b: bytes.Bytes = bytes.from_cstr(cpath)+ val marker: str.StringView = files.join(str.view(cpath, @strlen(cpath)), ".vein/format")+ val found: bool = files.exists_file(marker)+ files.free_path(marker)+ if found {+ return some Repo{root: root_b}+ }+ val last: mut i64 = (@strlen(cpath) as i64) - 1+ for last >= 0 {+ val c: u8 = trust @load8(@ptradd(cpath, last))+ if c == 47 {+ break+ }+ last = last - 1+ }+ if last <= 0 {+ val p: mut ref void = cpath as ref void+ trust @free(p)+ return none+ }+ trust @store8(@ptradd(cpath, last), 0)+ }+ return none+}++pub fn vein_dir(r: Repo) str.StringView = {+ return files.join(root_view(r), ".vein")+}++pub fn packs_dir(r: Repo) str.StringView = {+ return files.join(root_view(r), ".vein/store/packs")+}++pub fn tmp_dir(r: Repo) str.StringView = {+ return files.join(root_view(r), ".vein/store/tmp")+}++pub fn op_heads_dir(r: Repo) str.StringView = {+ return files.join(root_view(r), ".vein/op_heads")+}++pub fn config_path(r: Repo) str.StringView = {+ return files.join(root_view(r), ".vein/config")+}++pub fn format_path(r: Repo) str.StringView = {+ return files.join(root_view(r), ".vein/format")+}++fn mkdirs_under(r: Repo, sub: str.StringView) bool = {+ val p: str.StringView = files.join(root_view(r), sub)+ val created: bool = files.mkdir_all(p)+ files.free_path(p)+ return created+}++/// Create a repository at `root`. Idempotent when the format file exists.+pub fn init(root: str.StringView) result[Repo, i32] = {+ if !files.exists_dir(root) {+ if !files.mkdir_all(root) {+ return err 12+ }+ }+ val cpath: ref u8 = canonical(root)+ if cpath == none {+ return err 1+ }+ val repo: Repo = Repo{root: bytes.from_cstr(cpath)}+ val format: str.StringView = format_path(repo)+ if files.exists_file(format) {+ val existing = files.read_all(format)+ files.free_path(format)+ if existing is some data {+ val same: bool = bytes.Bytes.eql(data, format_text())+ files.free_buffer(data)+ if !same {+ free_repo(repo)+ return err 2+ }+ return ok repo+ }+ free_repo(repo)+ return err 3+ }+ files.free_path(format)++ if !mkdirs_under(repo, ".vein") {+ free_repo(repo)+ return err 4+ }+ if !mkdirs_under(repo, ".vein/store") {+ free_repo(repo)+ return err 13+ }+ if !mkdirs_under(repo, ".vein/store/packs") {+ free_repo(repo)+ return err 5+ }+ if !mkdirs_under(repo, ".vein/store/tmp") {+ free_repo(repo)+ return err 6+ }+ if !mkdirs_under(repo, ".vein/op_heads") {+ free_repo(repo)+ return err 7+ }+ if !mkdirs_under(repo, ".vein/git-map") {+ free_repo(repo)+ return err 8+ }+ if !mkdirs_under(repo, ".vein/working_copy") {+ free_repo(repo)+ return err 9+ }+ if !mkdirs_under(repo, ".vein/resolutions") {+ free_repo(repo)+ return err 10+ }++ val fp: str.StringView = format_path(repo)+ val wrote: bool = files.write_all(fp, format_text())+ files.free_path(fp)+ if !wrote {+ free_repo(repo)+ return err 11+ }+ val cp: str.StringView = config_path(repo)+ if !files.exists_file(cp) {+ val empty: bytes.Bytes = bytes.empty()+ files.write_all(cp, empty)+ }+ files.free_path(cp)+ return ok repo+}--- /dev/null+++ b/src/src/store/pack.sx@@ -0,0 +1,359 @@+/// Pack files (`vpack`): immutable, independently compressed object records.++val bytes = use("../core/bytes.sx")+val buf = use("../core/buf.sx")+val reader = use("../core/reader.sx")+val derr = use("../core/error.sx")+val prim = use("../core/primitives.sx")+val lists = use("../core/lists.sx")+val objid = use("../object/id.sx")+val types = use("../object/types.sx")+val raw = use("../object/raw.sx")+val records = use("records.sx")+val index = use("index.sx")+val zstd = use("zstd.sx")+val b3 = use("../crypto/blake3.sx")++pub val PACK_FORMAT_VERSION: u32 = 1+pub val PACK_HEADER_LEN: usize = 16+pub val RECORD_MIN: usize = 36++pub type Pack = {+ data: mut bytes.Bytes+ count: mut usize+ ids: mut ref u8+ kinds: mut ref u8+ comps: mut ref u8+ raw_lens: mut ref u8+ stored_lens: mut ref u8+ data_offs: mut ref u8+ rec_offs: mut ref u8+ trailer: mut bytes.Bytes+}++pub type PackOutput = {+ pack: bytes.Bytes+ index: bytes.Bytes+ name: bytes.Bytes+ count: usize+}++pub fn (Pack) id_at(p: self, i: usize) objid.Id = {+ pre {+ in_bounds: i < p.count+ }+ return objid.id(trust @ptradd(p.ids, (i * 32) as i64))+}++pub fn (Pack) kind_at(p: self, i: usize) u8 = {+ pre {+ in_bounds: i < p.count+ }+ return trust @load8(@ptradd(p.kinds, i as i64))+}++pub fn (Pack) comp_at(p: self, i: usize) u8 = {+ pre {+ in_bounds: i < p.count+ }+ return trust @load8(@ptradd(p.comps, i as i64))+}++pub fn (Pack) raw_len_at(p: self, i: usize) u64 = {+ pre {+ in_bounds: i < p.count+ }+ return trust @load64(@ptradd(p.raw_lens, (i * 8) as i64)) as u64+}++pub fn (Pack) stored_len_at(p: self, i: usize) u64 = {+ pre {+ in_bounds: i < p.count+ }+ return trust @load64(@ptradd(p.stored_lens, (i * 8) as i64)) as u64+}++pub fn (Pack) data_off_at(p: self, i: usize) u64 = {+ pre {+ in_bounds: i < p.count+ }+ return trust @load64(@ptradd(p.data_offs, (i * 8) as i64)) as u64+}++pub fn (Pack) rec_off_at(p: self, i: usize) u64 = {+ pre {+ in_bounds: i < p.count+ }+ return trust @load64(@ptradd(p.rec_offs, (i * 8) as i64)) as u64+}++/// Find the record whose start offset is `off`. Record offsets are ascending.+pub fn (Pack) find_by_offset(p: self, off: u64) option[usize] = {+ val lo: mut usize = 0+ val hi: mut usize = p.count+ for lo < hi {+ val mid: usize = lo + (hi - lo) / 2+ val cur: u64 = Pack.rec_off_at(p, mid)+ if cur == off {+ return some mid+ }+ if cur < off {+ lo = mid + 1+ } else {+ hi = mid+ }+ }+ return none+}++pub fn (Pack) stored(p: self, i: usize) bytes.Bytes = {+ pre {+ in_bounds: i < p.count+ }+ val off: usize = Pack.data_off_at(p, i) as usize+ val n: usize = Pack.stored_len_at(p, i) as usize+ return bytes.Bytes.slice(p.data, off, off + n)+}++pub fn free_pack(p: ref Pack) void = {+ files_free(p.data)+ trust @free(p.ids as ref void)+ trust @free(p.kinds as ref void)+ trust @free(p.comps as ref void)+ trust @free(p.raw_lens as ref void)+ trust @free(p.stored_lens as ref void)+ trust @free(p.data_offs as ref void)+ trust @free(p.rec_offs as ref void)+ val q: mut ref void = p as ref void+ trust @free(q)+}++fn files_free(b: bytes.Bytes) void = {+ if b.ptr != none {+ val p: mut ref void = b.ptr as ref void+ trust @free(p)+ }+}++fn type_limit(t: u8) usize = {+ if t == types.CHUNK {+ return prim.MAX_CHUNK_LEN+ }+ return prim.MAX_OBJECT_BODY+}++/// Decode and structurally verify a pack. Record hashes are verified by the+/// caller (and by fsck); this function checks the container only.+pub fn decode(data: bytes.Bytes) result[ref Pack, derr.DecodeError] = trust {+ if data.len < PACK_HEADER_LEN + 32 {+ return err derr.fail(derr.ErrorKind.UnexpectedEnd, 0)+ }+ if !bytes.Bytes.eql(bytes.Bytes.slice(data, 0, 4), bytes.bytes(c"VPK1", 4)) {+ return err derr.fail(derr.ErrorKind.InvalidMagic, 0)+ }+ val version: u32 = @load32(@ptradd(data.ptr, 4)) as u32+ if version != PACK_FORMAT_VERSION {+ return err derr.fail(derr.ErrorKind.UnsupportedVersion, 4)+ }+ val count_u64: u64 = @load64(@ptradd(data.ptr, 8)) as u64+ val body_end: usize = data.len - 32+ val trailer: bytes.Bytes = bytes.Bytes.slice(data, body_end, data.len)++ val digest: ref u8 = @alloc(32) as ref u8+ b3.hash(data.ptr, body_end, digest)+ val valid: bool = bytes.Bytes.eql(bytes.bytes(digest, 32), trailer)+ @free(digest as ref void)+ if !valid {+ return err derr.fail(derr.ErrorKind.HashMismatch, body_end)+ }++ if count_u64 > (body_end as u64) / (RECORD_MIN as u64) {+ return err derr.fail(derr.ErrorKind.LimitExceeded, 8)+ }+ val count: usize = count_u64 as usize+ val ids: ref u8 = @alloc(count * 32) as ref u8+ val kinds: ref u8 = @alloc(count) as ref u8+ val comps: ref u8 = @alloc(count) as ref u8+ val raw_lens: ref u8 = @alloc(count * 8) as ref u8+ val stored_lens: ref u8 = @alloc(count * 8) as ref u8+ val data_offs: ref u8 = @alloc(count * 8) as ref u8+ val rec_offs: ref u8 = @alloc(count * 8) as ref u8++ val r: mut reader.Reader = reader.new(data.ptr, body_end)+ r.pos = PACK_HEADER_LEN+ val i: mut usize = 0+ for i < count {+ val rec_off: usize = reader.Reader.offset(r)+ val idp: ref u8 = reader.Reader.read_id(r)?+ @memcpy(@ptradd(ids, (i * 32) as i64), idp as ref void, 32)+ @store64(@ptradd(rec_offs, (i * 8) as i64), rec_off as u64)++ val kind: u8 = reader.Reader.read_u8(r)?+ if !types.is_valid(kind) {+ return err derr.fail(derr.ErrorKind.InvalidValue, reader.Reader.offset(r) - 1)+ }+ val comp: u8 = reader.Reader.read_u8(r)?+ if comp > 1 {+ return err derr.fail(derr.ErrorKind.InvalidValue, reader.Reader.offset(r) - 1)+ }+ val at: usize = reader.Reader.offset(r)+ val raw_len: u64 = reader.Reader.read_varint(r)?+ val stored_len: u64 = reader.Reader.read_varint(r)?+ if raw_len == 0 {+ return err derr.fail(derr.ErrorKind.InvalidValue, at)+ }+ if raw_len > type_limit(kind) as u64 {+ return err derr.fail(derr.ErrorKind.LimitExceeded, at)+ }+ if comp == 0 && raw_len != stored_len {+ return err derr.fail(derr.ErrorKind.InvalidValue, at)+ }+ if stored_len > reader.Reader.remaining(r) as u64 {+ return err derr.fail(derr.ErrorKind.UnexpectedEnd, at)+ }+ @store8(@ptradd(kinds, i as i64), kind)+ @store8(@ptradd(comps, i as i64), comp)+ @store64(@ptradd(raw_lens, (i * 8) as i64), raw_len)+ @store64(@ptradd(stored_lens, (i * 8) as i64), stored_len)+ @store64(@ptradd(data_offs, (i * 8) as i64), reader.Reader.offset(r) as u64)+ val _ = reader.Reader.read_raw(r, stored_len as usize)?+ i = i + 1+ }+ if reader.Reader.offset(r) != body_end {+ return err derr.fail(derr.ErrorKind.TrailingBytes, reader.Reader.offset(r))+ }++ val p: mut ref Pack = @alloc(@sizeof(Pack)) as ref Pack+ p.data = data+ p.count = count+ p.ids = ids+ p.kinds = kinds+ p.comps = comps+ p.raw_lens = raw_lens+ p.stored_lens = stored_lens+ p.data_offs = data_offs+ p.rec_offs = rec_offs+ p.trailer = trailer+ return ok p+}++/// Decompress or copy one record body. The returned buffer is owned.+pub fn get(p: ref Pack, i: usize) result[bytes.Bytes, derr.DecodeError] = {+ pre {+ in_bounds: i < p.count+ }+ val raw_len: usize = Pack.raw_len_at(p, i) as usize+ if raw_len == 0 {+ return ok bytes.empty()+ }+ val comp: u8 = Pack.comp_at(p, i)+ val stored: bytes.Bytes = Pack.stored(p, i)+ if comp == 0 {+ val out: ref u8 = @alloc(raw_len) as ref u8+ trust @memcpy(out as ref void, stored.ptr as ref void, raw_len)+ return ok bytes.bytes(out, raw_len)+ }+ val decoded = zstd.decompress(stored, raw_len)+ if decoded is some d {+ return ok d+ }+ return err derr.fail(derr.ErrorKind.Corrupt, Pack.data_off_at(p, i) as usize)+}++fn id_in(seen: list[objid.Id], id: objid.Id) bool = {+ for x in seen {+ if objid.Id.eql(x, id) {+ return true+ }+ }+ return false+}++fn free_id(id: objid.Id) void = {+ if id.ptr != none {+ val p: mut ref void = id.ptr as ref void+ trust @free(p)+ }+}+++/// Build a pack and its index from a set of objects. Duplicate object IDs are+/// written once. The caller owns the returned buffers.+pub fn encode(objects: list[ref raw.RawObject]) PackOutput = {+ val seen: mut list[objid.Id] = lists.new[objid.Id]()+ val metas: mut list[ref records.RecordMeta] = lists.new[ref records.RecordMeta]()+ val b: mut buf.Buf = buf.new(4096)+ buf.Buf.put_raw(b, c"VPK1", 4)+ buf.Buf.put_u32_le(b, PACK_FORMAT_VERSION)+ buf.Buf.put_u64_le(b, 0)++ for o in objects {+ if !types.is_valid(o.type_byte) {+ continue+ }+ val id: objid.Id = objid.object_id(o.type_byte, o.body)+ if id_in(seen, id) {+ free_id(id)+ continue+ }+ @append(seen, id)+ val offset: u64 = b.len as u64+ val compressed: bytes.Bytes = zstd.compress(o.body, zstd.DEFAULT_LEVEL)+ val comp: mut u8 = 0+ val stored: mut bytes.Bytes = o.body+ if compressed.len > 0 {+ comp = 1+ stored = compressed+ }+ buf.Buf.put_id(b, id.ptr)+ buf.Buf.put_u8(b, o.type_byte)+ buf.Buf.put_u8(b, comp)+ buf.Buf.put_varint(b, o.body.len as u64)+ buf.Buf.put_varint(b, stored.len as u64)+ buf.Buf.put_bytes(b, stored)+ if compressed.len > 0 {+ val p: mut ref void = compressed.ptr as ref void+ trust @free(p)+ }+ @append(metas, records.record_meta(id, offset, o.type_byte, o.body.len as u64))+ }++ trust @store64(@ptradd(b.ptr, 8), @len(metas) as u64)+ val digest: ref u8 = @alloc(32) as ref u8+ trust b3.hash(b.ptr, b.len, digest)+ buf.Buf.put_raw(b, digest, 32)+ trust @free(digest as ref void)++ val pack_bytes: bytes.Bytes = bytes.Bytes.dup(buf.Buf.view(b))+ val pack_trailer: bytes.Bytes = bytes.Bytes.slice(pack_bytes, pack_bytes.len - 32, pack_bytes.len)+ records.sort_by_id(metas)+ val index_bytes: bytes.Bytes = index.encode(metas, pack_trailer)++ val name_hex: ref u8 = @alloc(65) as ref u8+ objid.hex_encode(pack_trailer.ptr, 32, name_hex)+ trust @store8(@ptradd(name_hex, 64), 0)+ val name: bytes.Bytes = bytes.bytes(name_hex, 64)++ val n: usize = @len(metas)+ buf.Buf.free(b)+ for m in metas {+ val p: mut ref void = m as ref void+ trust @free(p)+ }+ @listfree(metas)+ for x in seen {+ free_id(x)+ }+ @listfree(seen)++ return PackOutput{pack: pack_bytes, index: index_bytes, name: name, count: n}+}++pub fn free_output(o: PackOutput) void = {+ val a: mut ref void = o.pack.ptr as ref void+ trust @free(a)+ val b: mut ref void = o.index.ptr as ref void+ trust @free(b)+ val c: mut ref void = o.name.ptr as ref void+ trust @free(c)+}--- /dev/null+++ b/src/src/store/records.sx@@ -0,0 +1,71 @@+/// Metadata kept per object while a pack and its index are built.++val objid = use("../object/id.sx")++pub type RecordMeta = {+ id: mut objid.Id+ offset: mut u64+ type_byte: mut u8+ raw_len: mut u64+}++pub fn record_meta(+ id: objid.Id,+ offset: u64,+ type_byte: u8,+ raw_len: u64+) ref RecordMeta = {+ val r: mut ref RecordMeta = @alloc(@sizeof(RecordMeta)) as ref RecordMeta+ r.id = id+ r.offset = offset+ r.type_byte = type_byte+ r.raw_len = raw_len+ return r+}++fn at(records: list[ref RecordMeta], i: usize) ref RecordMeta = {+ val o = @get(records, i)+ if o is some v {+ return v+ }+ assert false+ return none+}++fn swap(a: mut ref RecordMeta, b: mut ref RecordMeta) void = {+ val id: objid.Id = a.id+ val off: u64 = a.offset+ val ty: u8 = a.type_byte+ val rl: u64 = a.raw_len+ a.id = b.id+ a.offset = b.offset+ a.type_byte = b.type_byte+ a.raw_len = b.raw_len+ b.id = id+ b.offset = off+ b.type_byte = ty+ b.raw_len = rl+}++/// Selection sort by object ID. Record counts per pack are modest in M0; the+/// sort is allocation-free.+pub fn sort_by_id(records: list[ref RecordMeta]) void = {+ val n: usize = @len(records)+ val i: mut usize = 0+ for i < n {+ val min: mut usize = i+ val j: mut usize = i + 1+ for j < n {+ val rj = at(records, j)+ val rmin = at(records, min)+ if objid.Id.cmp(rj.id, rmin.id) < 0 {+ min = j+ }+ j = j + 1+ }+ if min != i {+ swap(at(records, i), at(records, min))+ }+ i = i + 1+ }+}--- /dev/null+++ b/src/src/store/store.sx@@ -0,0 +1,312 @@+/// In-memory view of a repository's packs, plus pack writing.++val str = use("std/string")+val bytes = use("../core/bytes.sx")+val lists = use("../core/lists.sx")+val derr = use("../core/error.sx")+val objid = use("../object/id.sx")+val raw = use("../object/raw.sx")+val pack = use("pack.sx")+val index = use("index.sx")+val layout = use("layout.sx")+val files = use("../io/files.sx")+val native = use("../io/native.sx")++pub type Handle = {+ path: mut str.StringView+ pack: mut ref pack.Pack+ idx: mut ref index.Index+}++pub type Store = {+ handles: mut list[ref Handle]+}++pub type Loc = {+ pack_index: mut usize+ record_index: mut usize+ kind: mut u8+}++pub fn new_store() Store = {+ return Store{handles: lists.new[ref Handle]()}+}++pub fn add_handle(+ handles: mut list[ref Handle],+ path: str.StringView,+ p: ref pack.Pack,+ idx: ref index.Index+) void = {+ val h: mut ref Handle = @alloc(@sizeof(Handle)) as ref Handle+ h.path = path+ h.pack = p+ h.idx = idx+ @append(handles, h)+}++pub fn add(store: mut Store, path: str.StringView, p: ref pack.Pack, idx: ref index.Index) void = {+ add_handle(store.handles, path, p, idx)+}++pub fn close_handles(handles: list[ref Handle]) void = {+ for h in handles {+ pack.free_pack(h.pack)+ index.free_index(h.idx)+ files.free_path(h.path)+ val p: mut ref void = h as ref void+ trust @free(p)+ }+ @listfree(handles)+}++pub fn close(store: Store) void = {+ close_handles(store.handles)+}++pub fn handle_at(store: Store, i: usize) ref Handle = {+ val o = @get(store.handles, i)+ if o is some h {+ return h+ }+ assert false+ return none+}++/// Find an object across a list of loaded packs. Returns true and fills `out`+/// when found. Using an out-parameter avoids returning a large option payload+/// across a function boundary.+pub fn find_handles(+ handles: list[ref Handle],+ id: objid.Id,+ out: mut Loc+) bool = {+ val i: mut usize = 0+ for i < @len(handles) {+ val h = handle_list_at(handles, i)+ val found = index.Index.find(h.idx, id)+ if found is some pos {+ val off: u64 = index.Index.offset_at(h.idx, pos)+ val rec = pack.Pack.find_by_offset(h.pack, off)+ if rec is some r {+ val pidx: usize = i+ val ridx: usize = r+ val kk: u8 = pack.Pack.kind_at(h.pack, ridx)+ out.pack_index = pidx+ out.record_index = ridx+ out.kind = kk+ return true+ }+ }+ i = i + 1+ }+ return false+}++/// Compatibility wrapper for callers that prefer an option.+pub fn lookup_handles(handles: list[ref Handle], id: objid.Id) option[Loc] = {+ val out: mut Loc = Loc{pack_index: 0, record_index: 0, kind: 0}+ if find_handles(handles, id, out) {+ return some out+ }+ return none+}++/// Find an object across all loaded packs.+pub fn lookup(store: Store, id: objid.Id) option[Loc] = {+ return lookup_handles(store.handles, id)+}++pub fn handle_list_at(handles: list[ref Handle], i: usize) ref Handle = {+ val o = @get(handles, i)+ if o is some h {+ return h+ }+ assert false+ return none+}++pub fn get_handles(+ handles: list[ref Handle],+ loc: Loc+) result[bytes.Bytes, derr.DecodeError] = {+ pre {+ pack_in_bounds: loc.pack_index < @len(handles)+ }+ val h = handle_list_at(handles, loc.pack_index)+ return pack.get(h.pack, loc.record_index)+}++pub fn get(store: Store, loc: Loc) result[bytes.Bytes, derr.DecodeError] = {+ return get_handles(store.handles, loc)+}++fn load_pair(+ packs_dir: str.StringView,+ name: str.StringView+) option[Handle] = {+ val pview: str.StringView = files.join(packs_dir, name)+ val pdata_opt = files.read_all(pview)+ if pdata_opt is none {+ files.free_path(pview)+ return none+ }+ val pdata: mut bytes.Bytes = bytes.empty()+ match pdata_opt {+ some d => {+ pdata = d+ }+ none => {+ files.free_path(pview)+ return none+ }+ }+ val p = trust pack.decode(pdata)+ val pp: mut ref pack.Pack = none+ match p {+ ok x => {+ pp = x+ }+ err _ => {+ files.free_buffer(pdata)+ files.free_path(pview)+ return none+ }+ }+ if name.len <= 6 {+ pack.free_pack(pp)+ files.free_path(pview)+ return none+ }+ val base: str.StringView = str.view(name.ptr, name.len - 6)+ val iname: str.StringView = files.with_suffix(base, ".vidx")+ val iview: str.StringView = files.join(packs_dir, iname)+ files.free_path(iname)+ val idata_opt = files.read_all(iview)+ if idata_opt is none {+ pack.free_pack(pp)+ files.free_path(pview)+ files.free_path(iview)+ return none+ }+ val idata: mut bytes.Bytes = bytes.empty()+ match idata_opt {+ some d => {+ idata = d+ }+ none => {+ pack.free_pack(pp)+ files.free_path(pview)+ files.free_path(iview)+ return none+ }+ }+ val idxr = index.decode(idata, pp.trailer)+ val idx: mut ref index.Index = none+ match idxr {+ ok x => {+ idx = x+ }+ err _ => {+ files.free_buffer(idata)+ pack.free_pack(pp)+ files.free_path(pview)+ files.free_path(iview)+ return none+ }+ }+ files.free_path(iview)+ val h: mut ref Handle = @alloc(@sizeof(Handle)) as ref Handle+ h.path = pview+ h.pack = pp+ h.idx = idx+ return some h+}++/// Load every valid pack/index pair. Invalid pairs are skipped; `fsck` reports+/// them in detail.+pub fn open_all(repo: layout.Repo) Store = {+ val store: mut Store = new_store()+ val dir: str.StringView = layout.packs_dir(repo)+ val names: list[ref u8] = files.list_dir(dir)+ for n in names {+ val nv: str.StringView = str.from_cstr(n)+ if files.name_ends_with(n, c".vpack") {+ val h = load_pair(dir, nv)+ if h is some handle {+ @append(store.handles, handle)+ }+ }+ }+ files.free_names(names)+ files.free_path(dir)+ return store+}++/// Write one pack and its index durably.+pub fn write_pack(repo: layout.Repo, objects: list[ref raw.RawObject]) bool = {+ val out: pack.PackOutput = pack.encode(objects)+ val dir: str.StringView = layout.packs_dir(repo)+ val tmpd: str.StringView = layout.tmp_dir(repo)+ val base: str.StringView = str.view(out.name.ptr, out.name.len as i64)++ val pack_suffix: str.StringView = files.with_suffix(base, ".vpack")+ val idx_suffix: str.StringView = files.with_suffix(base, ".vidx")+ val ptmp_suffix: str.StringView = files.with_suffix(base, ".vpack.tmp")+ val itmp_suffix: str.StringView = files.with_suffix(base, ".vidx.tmp")++ val pfinal: str.StringView = files.join(dir, pack_suffix)+ val ifinal: str.StringView = files.join(dir, idx_suffix)+ val ptmp: str.StringView = files.join(tmpd, ptmp_suffix)+ val itmp: str.StringView = files.join(tmpd, itmp_suffix)++ val wrote_pack: bool = native.write_atomic(ptmp, pfinal, tmpd, dir, out.pack)+ val wrote_index: mut bool = false+ if wrote_pack {+ wrote_index = native.write_atomic(itmp, ifinal, tmpd, dir, out.index)+ if !wrote_index {+ files.delete(pfinal)+ }+ }++ files.free_path(pfinal)+ files.free_path(ifinal)+ files.free_path(ptmp)+ files.free_path(itmp)+ files.free_path(pack_suffix)+ files.free_path(idx_suffix)+ files.free_path(ptmp_suffix)+ files.free_path(itmp_suffix)+ files.free_path(dir)+ files.free_path(tmpd)+ pack.free_output(out)+ return wrote_pack && wrote_index+}++fn contains(hay: bytes.Bytes, needle: bytes.Bytes) bool = {+ if needle.len > hay.len {+ return false+ }+ val limit: usize = hay.len - needle.len+ val i: mut usize = 0+ for i <= limit {+ if bytes.Bytes.eql(bytes.Bytes.slice(hay, i, i + needle.len), needle) {+ return true+ }+ i = i + 1+ }+ return false+}++/// True when the local config names a promisor remote.+pub fn has_promisor(repo: layout.Repo) bool = {+ val cfgp: str.StringView = layout.config_path(repo)+ val data = files.read_all(cfgp)+ files.free_path(cfgp)+ if data is some d {+ val found: bool = contains(d, bytes.bytes(c"promisor", 8))+ files.free_buffer(d)+ return found+ }+ return false+}--- /dev/null+++ b/src/src/store/zstd.sx@@ -0,0 +1,72 @@+/// zstd bindings used by pack records.+///+/// Records are compressed independently. A record that would not shrink is+/// stored uncompressed, which the caller signals by freeing the compression+/// result and writing the raw bytes.++lib "zstd"++val bytes = use("../core/bytes.sx")++extern (C) fn ZSTD_compressBound(src_size: usize) usize = "ZSTD_compressBound"+extern (C) fn ZSTD_compress(+ dst: ref void,+ dst_capacity: usize,+ src: ref void,+ src_size: usize,+ level: i32+) usize = "ZSTD_compress"+extern (C) fn ZSTD_decompress(+ dst: ref void,+ dst_capacity: usize,+ src: ref void,+ compressed_size: usize+) usize = "ZSTD_decompress"+extern (C) fn ZSTD_isError(code: usize) u32 = "ZSTD_isError"++pub val DEFAULT_LEVEL: i32 = 3++/// Compress `src`. Returns an empty span when compression fails or does not+/// reduce the size.+pub fn compress(src: bytes.Bytes, level: i32) bytes.Bytes = {+ if src.len == 0 {+ return bytes.empty()+ }+ val bound: usize = trust ZSTD_compressBound(src.len)+ if bound == 0 {+ return bytes.empty()+ }+ val dst: ref u8 = @alloc(bound) as ref u8+ val n: usize = trust ZSTD_compress(+ dst as ref void,+ bound,+ src.ptr as ref void,+ src.len,+ level+ )+ if trust ZSTD_isError(n) != 0 || n >= src.len {+ trust @free(dst as ref void)+ return bytes.empty()+ }+ return bytes.bytes(dst, n)+}++/// Decompress exactly `raw_len` bytes. Fails when the stream is malformed or+/// produces a different length.+pub fn decompress(src: bytes.Bytes, raw_len: usize) option[bytes.Bytes] = {+ if raw_len == 0 {+ return none+ }+ val dst: ref u8 = @alloc(raw_len) as ref u8+ val n: usize = trust ZSTD_decompress(+ dst as ref void,+ raw_len,+ src.ptr as ref void,+ src.len+ )+ if trust ZSTD_isError(n) != 0 || n != raw_len {+ trust @free(dst as ref void)+ return none+ }+ return some bytes.bytes(dst, raw_len)+}--- a/src/sx.mod+++ b/src/sx.mod@@ -4,9 +4,15 @@ build release { flags "-release"- output "./vein"+ output "./vn"+ windows {+ output "vn.exe"+ } } build dev {- output "./vein-dev"+ output "./vn-dev"+ windows {+ output "vn-dev.exe"+ } }