navid/veins / commit
6c29333dcac4
Navid M <navidmomtahen@gmail.com> · 2026-11-26
parents: fddc5b75699f
Browse files at this commit · Download source
--- a/src/.gitignore+++ /dev/null@@ -1,9 +0,0 @@-vn-dev-vn-veins-dev-SPECTRE_LANGUAGE_REFERENCE.md-lib/-std__*-s-out/-docs-out*/-.sxb/--- a/src/build-native.sh+++ /dev/null@@ -1,32 +0,0 @@-#!/bin/sh-# Build the native hot-path objects and combine them for spectre -link-obj.-set -e--out="${1:-.sxb/linux.x86_64}"-cc="${CC:-cc}"-mkdir -p "$out"--crypto="src/crypto"-b3="$crypto/blake3"--"$cc" -O3 -c "$crypto/blake3_c.c" -o "$out/blake3_c.o"-"$cc" -O3 -c "$b3/blake3.c" -o "$out/blake3_impl.o"-"$cc" -O3 -c "$b3/blake3_dispatch.c" -o "$out/blake3_dispatch.o"-"$cc" -O3 -c "$b3/blake3_portable.c" -o "$out/blake3_portable.o"-"$cc" -O3 -msse2 -c "$b3/blake3_sse2.c" -o "$out/blake3_sse2.o"-"$cc" -O3 -msse4.1 -c "$b3/blake3_sse41.c" -o "$out/blake3_sse41.o"-"$cc" -O3 -mavx2 -c "$b3/blake3_avx2.c" -o "$out/blake3_avx2.o"-"$cc" -O3 -mavx512f -mavx512vl -c "$b3/blake3_avx512.c" -o "$out/blake3_avx512.o"-"$cc" -O3 -c "src/chunking/fastcdc_c.c" -o "$out/fastcdc_c.o"--"$cc" -r \- "$out/blake3_c.o" \- "$out/blake3_impl.o" \- "$out/blake3_dispatch.o" \- "$out/blake3_portable.o" \- "$out/blake3_sse2.o" \- "$out/blake3_sse41.o" \- "$out/blake3_avx2.o" \- "$out/blake3_avx512.o" \- "$out/fastcdc_c.o" \- -o "$out/veins_native.o"--- a/src/src/chunking/fastcdc.sx+++ /dev/null@@ -1,41 +0,0 @@-/// 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")--extern (C) fn vn_fastcdc_next(data: ref u8, len: usize, gear: ref u8) usize = "vn_fastcdc_next"--pub val (- MIN_SIZE: usize = 16384- AVG_SIZE: usize = 65536- MAX_SIZE: usize = 262144- NORMALIZATION: usize = 2-)--/// 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 = trust {- pre {- progress: len > 0- }- return vn_fastcdc_next(data, len, gear.GEAR_RAW)-}--/// Split a byte span into chunk lengths.-pub fn split(data: ref u8, len: usize) list[usize] = trust {- val out: mut list[usize] = lists.new[usize]()- val off: mut usize = 0- for off < len {- val n: usize = next_len(@ptradd(data, off as i64), len - off)- @append(out, n)- off = off + n- }- return out-}--- a/src/src/chunking/fastcdc_c.c+++ /dev/null@@ -1,39 +0,0 @@-/* FastCDC next-chunk scan used by the format's chunker. */--#include <stddef.h>-#include <stdint.h>-#include <string.h>--#define VN_CDC_MIN 16384-#define VN_CDC_AVG 65536-#define VN_CDC_MAX 262144-#define VN_CDC_MASK_S 0x3ffffULL-#define VN_CDC_MASK_L 0x3fffULL--static uint64_t gear_at(const uint8_t *gear, uint8_t c) {- uint64_t v;- memcpy(&v, gear + (size_t)c * 8, sizeof(v));- return v;-}--size_t vn_fastcdc_next(const uint8_t *data, size_t len, const uint8_t *gear) {- if (len <= VN_CDC_MIN) {- return len;- }- size_t limit = len < VN_CDC_MAX ? len : VN_CDC_MAX;- size_t normal = VN_CDC_AVG < limit ? VN_CDC_AVG : limit;- uint64_t fp = 0;- for (size_t i = VN_CDC_MIN; i < normal; i++) {- fp = (fp >> 1) + gear_at(gear, data[i]);- if ((fp & VN_CDC_MASK_S) == 0) {- return i + 1;- }- }- for (size_t i = normal; i < limit; i++) {- fp = (fp >> 1) + gear_at(gear, data[i]);- if ((fp & VN_CDC_MASK_L) == 0) {- return i + 1;- }- }- return limit;-}Binary files a/src/src/chunking/gear.bin and b/src/src/chunking/gear.bin differ--- a/src/src/chunking/gear.sx+++ /dev/null@@ -1,78 +0,0 @@-/// FastCDC gear table for veins format version 1.-///-/// The 256 entries are derived deterministically, so that independent-/// implementations can reproduce them:-///-/// gear[i] = u64le(BLAKE3("veins/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 = [- 0xf8447b379cdadcd5, 0xbe63d125aec8ca6d, 0x10bcf6f7c33cbed3, 0x2b6ba7e5a572be1b,- 0x145ba610bca60ff6, 0x335db29c88ea2545, 0xaf7ab78b34ea1c8f, 0x04383fe20dcbf16a,- 0x542c3ed8a305a2e4, 0x8306bb8ba52f1966, 0x64abea4024164cb2, 0xd5d28a2763a5c906,- 0xa709f38738243984, 0x0a1ac1c77c75aa83, 0x2fe3df4653145470, 0x8ef53a2c653fab0e,- 0xe6f0c2e4436fe0b0, 0xf387dc66d595a4fd, 0xd520313dc5c2ef0c, 0x3aa4df70dc7b4e20,- 0xfe89fa05b2229b26, 0xd5b811960c27b302, 0xd6b9a82445390552, 0x8c9df4eb17abefbb,- 0x8dddfb83b6f3e3f5, 0x0dfd5490314a4a77, 0xcd39d37f4fffeb07, 0xd953ec046f403aef,- 0xfd67339f7fb60679, 0x1673126b2d34af03, 0x810365172ff5c83f, 0x2e219c15c03a0ce6,- 0xcd2dd776c4dc8b37, 0x31a05022f6757ac7, 0xa54aaac64e2b7a4f, 0x541cc9dbe8ef6090,- 0x15f25ab7ac626796, 0x6a8743338a21c0db, 0x15856273cdeb225b, 0x92d3b90d24b0ceab,- 0xdb7ed64743e6bafd, 0x6a2371fe5845980b, 0x3ed2cbd1a12b1554, 0x26292f185e7ae5c2,- 0xcfa468695ae32b7c, 0x10c8ad9d7d37b38b, 0x0c93c73c9b8a5760, 0xdce731099879e3ac,- 0x948f5e10a859b0f9, 0x5b7b5381c2b61ad3, 0x032e2bccef396ec0, 0xcb04960d80779661,- 0x1800187b89406bba, 0x8cfeb1e5741f9b5b, 0xc0a8b6dd4ca2bc72, 0x7121d98743aad057,- 0x62122a734c7c30cf, 0x09dfc78344470469, 0x7dd2e6c3164e95cc, 0x1e081af5098f9f95,- 0xa060c1359428a17a, 0xfbbf087daa942d8d, 0x02befbb34a59cfa0, 0xf61aba2e56e7fcab,- 0xd201b08ba97b4f74, 0x05d1923c598bb943, 0x577cb1ac90c58fdc, 0x35714370655de214,- 0x9e875d6330c98d09, 0x580e31b7e5d121d1, 0x86e331d3a1868867, 0x7198d317f173adfc,- 0xd1d712f288f8f74f, 0x498eb6b5efeca820, 0x01609a0433de3ce6, 0xc6451604d3e5a30e,- 0x7cb8c805a7fc71d4, 0xabd48608b949d705, 0x80a7504b42991b37, 0xde2d8d960bc877d9,- 0x6658840c7b5680c4, 0x90ff0a9f74a67da4, 0x9c44badf508da6b7, 0x9399bf790bbe7784,- 0x984ef4f5cd8b44d9, 0x338a088febb6b2c4, 0x56b6457eba02a001, 0x69db87f3d877bc17,- 0xeaa4df254010fc26, 0xd4c46364dcfcc4c7, 0xf5f5ffa312012d68, 0xd56c6fd2995b3e2d,- 0x098e8ef0f3185a71, 0xd57d7c0096690b41, 0xd562d821200e0cd4, 0xbfba257d5a89b160,- 0x1058a4dfeffa765d, 0x74a5f76a74e5ca3c, 0xbcf278dd8ff805dc, 0x13696b2e934dd66f,- 0xa8e2ffed5d6c8f52, 0xc9711402212f8271, 0x83db1ae9a24b47f4, 0xfec127f15e6c1470,- 0x6e8185b3a8e5e1fc, 0xd503ce1f19ca76f8, 0x5e80dadee3f2c38a, 0x2d1ff7b2e1cb7079,- 0xf572fb19e969ef53, 0x502708c0febdf28c, 0x59f0859c330bd3ae, 0xfefb158359b5411f,- 0xbcbcce46e6c1b56d, 0x9fc6bd49258ef328, 0x89d3b5d6ba11aa7c, 0x4e44ee7a780f8aa6,- 0xcca6584b41c6a8dd, 0xbd39bf6f976088f1, 0x609df3f5f267e2cf, 0x970c32cd9b8f1f95,- 0x373a464e80f4734b, 0xfd01ca133c483c61, 0x317dfec1e4e54486, 0x653bb090e32d5fb8,- 0x0944739599bfa481, 0x33ee31072ab56364, 0xd3826c26bc20b44c, 0xd11f9251c67a66ac,- 0x79a81cf24d93662f, 0x9672efb77cb79214, 0x0b6852062b150542, 0x22cb8254926d5d21,- 0xf68817c5be91619e, 0x1fb235ed20504b6c, 0x7a00398632aae3d8, 0xd5cafd4331978a29,- 0xf80e0a5957bca856, 0x409ce1b813206914, 0xd0f1da7e99289a41, 0x2ede97d8000af47b,- 0x6a27ef6571d9b969, 0x97c4695b34247b16, 0x5ee4b2b0e7919e12, 0x73f02023b038ceed,- 0x54e24747c8dbc3f2, 0xea175f09cd4ea419, 0xa420b4e91e595736, 0xf58072b7aa16c147,- 0xc4eed8a665f16537, 0xefe95010907b5c71, 0x20b530bfb2fb6c5d, 0xa14f7dca9de676bd,- 0x899835e7943ffc24, 0x72cea269e19c9b60, 0xa2311c0586c3c70d, 0x5feb4a14932c2e90,- 0xbf24d7cf401f1a8c, 0xae081fd9aa06845a, 0x332ce9fca6bbb7df, 0xc4c0c4d9b89e0df2,- 0x2bddbc99fe5fb745, 0x533b9037add81672, 0x133ac755cf098a00, 0x8305c21cea592a03,- 0x2164728763c1f742, 0x8385d8702b7a940a, 0xb8b02364b0352c47, 0xd5535761e27bae91,- 0x930b49bf6552198f, 0xccd2c5d2f32ab8c6, 0x58c74b4b32fc9fa8, 0x98a324c44c1cd723,- 0x2abeecf0cfc735fc, 0x6419bb9739226916, 0xd9e94c1946307dd2, 0xe15622a475f6e038,- 0xc48fba22892a33bc, 0x0722a604b075bafc, 0x78889b342ff4560c, 0xdada1d3833b35bd6,- 0x4917f2c07311a5cc, 0x9d7685084873a92a, 0x5869edb9c4b4e78c, 0x30afc030f9d64382,- 0x548ed28c8845626f, 0x606be35894cbee13, 0xaaa4a0c60695574f, 0x364cf234a3dd2844,- 0x9aba0e81ff2f109c, 0x18d1e9b3fdfda42c, 0x1b9477ec5fb1ad36, 0x7f0136e7d6a3cb98,- 0x9a4e7496f95a6fbc, 0xb940293ab845abd6, 0xa1c6388ef0208374, 0x8da07493e7de1f8a,- 0xeeba605e6e273c4c, 0x3202537c27f4c285, 0xc40eebd30f194254, 0xdb3e091b83f3578b,- 0xef4d4e9267b4c82e, 0xce163a6c0f695d0d, 0x0b73d109498e2d9a, 0xb0ecccc0a05090a8,- 0x4748b37a01cd7c50, 0x75bedfaf04e09117, 0x4290c117203c922a, 0x0f4edf02e3d62367,- 0x9f88f3082a0860ef, 0x029e5bb038f506fa, 0xb4ff698bcd73d0ac, 0x61321d4822b1ebb9,- 0x997b0a0bfcbc4b7e, 0x669e117eb2fbc329, 0xc770e6b51cf723e1, 0x43e9c64d4ceba4fa,- 0x7089a98e8a61f669, 0x7635f6b39edd3638, 0x7efb2ec180815b1a, 0x599b9ba270412abe,- 0x099db42c6da84f07, 0xa80aa895e988a9e2, 0x857538709775368c, 0x0f35b67029f03082,- 0x29d1d07f6cdff719, 0x25f0c392a5184c13, 0xfab7c93869e72670, 0x57bfb01577cf7ea5,- 0xf243888561a284c9, 0x2cb309bd1f1e4f95, 0x860339add5cde62f, 0xb5c77be90a3bab2a,- 0x016359c3a034ab67, 0xf4426de9276d41b1, 0x1f0f25a49fb35408, 0xa216f9fe7f9a47d4,- 0xdf6ff4f9bc47eb4e, 0xde377b438cddb110, 0xa2bf999d31ef328f, 0x460eea338ffb2e84,- 0xf73ea9dde1297fa3, 0x05cb4964fec1213c, 0x7713be29f105fd3e, 0x6d6796f838c38ba2,- 0x8c8adb1031c0ae50, 0x526a7f116fe65583, 0xeabdacfe2ef6c020, 0x1c0de4493237857f,- 0xac655048637e992b, 0x2664f2bf04599664, 0x5cbe9c160f2f8c53, 0x1cc056978d12a1dc,- 0x889e35cb2ca6742f, 0xe0ab4043f6b783cc, 0x011128d888973e10, 0xfb74bdcd0afb54eb,-]--/// Byte view of the frozen table for fast FFI-free indexing.-pub val GEAR_RAW: ref u8 = @embed("gear.bin")--- a/src/src/cli/bench_cmd.sx+++ /dev/null@@ -1,210 +0,0 @@-/// Benchmark-only lazy import probe using the git CLI backend.--val str = use("std/string")-val stdio = use("std/stdio")-val msg = use("../core/msg.sx")-val time = use("std/time")-val bytes = use("../core/bytes.sx")-val buf = use("../core/buf.sx")-val idmap = use("../store/idmap.sx")-val files = use("../io/files.sx")--extern (C) fn popen(cmd: ref u8, mode: ref u8) ref void = "popen"-extern (C) fn pclose(stream: ref void) i32 = "pclose"-extern (C) fn fread(ptr: ref void, size: usize, n: usize, stream: ref void) usize = "fread"-extern (C) fn memchr(s: ref void, c: i32, n: usize) ref void = "memchr"--fn find_raw(p: ref u8, start: usize, end: usize, target: u8) usize = trust {- if start >= end {- return end- }- val hit: ref void = memchr(- @ptradd(p, start as i64) as ref void,- target as i32,- end - start- )- if hit == none {- return end- }- return @bitcast(hit, usize) - @bitcast(p, usize)-}--fn parse_size_raw(p: ref u8, start: usize, end: usize) usize = trust {- val n: mut usize = 0- val i: mut usize = start- for i < end {- val c: u8 = @load8(@ptradd(p, i as i64))- if c < 48 || c > 57 {- break- }- n = n * 10 + (c - 48) as usize- i++- }- return n-}--fn eq_raw(p: ref u8, start: usize, text: ref u8, n: usize) bool = trust {- val i: mut usize = 0- for i < n {- if @load8(@ptradd(p, (start + i) as i64)) != @load8(@ptradd(text, i as i64)) {- return false- }- i++- }- return true-}--fn capture(cmd: ref u8, out: mut buf.Buf) bool = trust {- val pipe = popen(cmd, c"r")- if pipe == none {- return false- }- val chunk: ref u8 = @alloc(65536) as ref u8- for {- val n: usize = fread(chunk as ref void, 1, 65536, pipe)- if n == 0 {- break- }- buf.Buf.put_raw(out, chunk, n)- }- @free(chunk as ref void)- pclose(pipe)- return true-}--pub fn run(args: list[ref u8], start: usize) i32 = trust {- if start >= @len(args) {- msg.error_prefix()- stdio.eprint("bench-import requires a git directory\n", {})- return 1- }- val repo_arg = @get(args, start)- val repo: mut str.StringView = str.from_cstr(c".")- if repo_arg is some r {- repo = str.from_cstr(r)- }- val repo_view: str.StringView = repo- val t0: i64 = time.now_ns()-- val listing: mut buf.Buf = buf.new(1048576)- val list_cmd: ref u8 = @fmtalloc(- "git --git-dir={s} rev-list --objects --all --filter=blob:none",- {repo_view}- )- val listed: bool = capture(list_cmd, listing)- @free(list_cmd as ref void)- if !listed {- buf.Buf.free(listing)- msg.error_prefix()- stdio.eprint("cannot run git rev-list\n", {})- return 1- }-- val meta_buf: mut buf.Buf = buf.new(65536)- val lp: ref u8 = listing.ptr- val llen: usize = listing.len- val pos: mut usize = 0- for pos < llen {- val eol: usize = find_raw(lp, pos, llen, 10)- val end: usize = find_raw(lp, pos, eol, 32)- if end > pos {- buf.Buf.put_raw(meta_buf, @ptradd(lp, pos as i64), end - pos)- buf.Buf.put_u8(meta_buf, 10)- }- pos = eol + 1- }- buf.Buf.free(listing)-- val meta_path: ref u8 = @fmtalloc("/tmp/veins-bench-meta-{d}.oids", {time.now_ns()})- val meta_view: str.StringView = str.from_cstr(meta_path)- val meta_written: bool = files.write_all(meta_view, buf.Buf.view(meta_buf))- buf.Buf.free(meta_buf)- if !meta_written {- @free(meta_path as ref void)- msg.error_prefix()- stdio.eprint("cannot write temporary commit/tree list\n", {})- return 1- }-- val data: mut buf.Buf = buf.new(1048576)- val batch_cmd: ref u8 = @fmtalloc(- "git --git-dir={s} cat-file --batch < {s}",- {repo_view, meta_view}- )- val batched: bool = capture(batch_cmd, data)- @free(batch_cmd as ref void)- if !batched {- buf.Buf.free(data)- files.delete(meta_view)- @free(meta_path as ref void)- msg.error_prefix()- stdio.eprint("cannot run git cat-file --batch\n", {})- return 1- }-- val key: ref u8 = @alloc(32) as ref u8- @memcpy(key as ref void, c"veins-gitoid", 12)- val lazy: mut idmap.IdSet = idmap.new(16384)- val commits: mut usize = 0- val trees: mut usize = 0- val entries: mut usize = 0- val lazy_count: mut usize = 0-- val dp: ref u8 = data.ptr- val dlen: usize = data.len- val p: mut usize = 0- for p < dlen {- val nl: usize = find_raw(dp, p, dlen, 10)- val sp1: usize = find_raw(dp, p, nl, 32)- val sp2: usize = find_raw(dp, sp1 + 1, nl, 32)- val size: usize = parse_size_raw(dp, sp2 + 1, nl)- val body_start: usize = nl + 1- val body_end: usize = body_start + size- val kind_len: usize = sp2 - sp1 - 1-- if kind_len == 6 && eq_raw(dp, sp1 + 1, c"commit", 6) {- commits++- } elif kind_len == 4 && eq_raw(dp, sp1 + 1, c"tree", 4) {- trees++- val ep: mut usize = body_start- for ep < body_end {- val space: usize = find_raw(dp, ep, body_end, 32)- val nul: usize = find_raw(dp, space + 1, body_end, 0)- val oid_start: usize = nul + 1- if oid_start + 20 > body_end {- break- }- val mode_len: usize = space - ep- val is_blob: bool = mode_len == 6- && @load8(@ptradd(dp, ep as i64)) == 49- && (@load8(@ptradd(dp, (ep + 1) as i64)) == 48- || @load8(@ptradd(dp, (ep + 1) as i64)) == 50)- if is_blob {- @memcpy(- @ptradd(key, 12) as ref void,- @ptradd(dp, oid_start as i64) as ref void,- 20- )- if idmap.put(lazy, bytes.bytes(key, 32)) {- lazy_count++- }- }- entries++- ep = oid_start + 20- }- }- p = body_end + 1- }- idmap.free(lazy)- @free(key as ref void)- buf.Buf.free(data)- files.delete(meta_view)- @free(meta_path as ref void)-- val ms: i64 = (time.now_ns() - t0) / 1000000- stdio.print(- "commits={d} trees={d} tree_entries={d} lazy_blobs={d} total={d}ms\n",- {commits, trees, entries, lazy_count, ms}- )- return 0-}--- a/src/src/cli/checkout_cmd.sx+++ /dev/null@@ -1,31 +0,0 @@-/// `vn checkout [rev]`: materialize a revision into the working directory.--val str = use("std/string")-val stdio = use("std/stdio")-val msg = use("../core/msg.sx")-val bytes = use("../core/bytes.sx")-val layout = use("../store/layout.sx")-val checkout = use("../worktree/checkout.sx")--pub fn run(args: list[ref u8], start: usize) i32 = trust {- val rev: mut bytes.Bytes = bytes.empty()- if start < @len(args) {- val r_opt = @get(args, start)- if r_opt is some r {- rev = bytes.from_cstr(r)- }- }- val repo_opt = layout.discover(str.from_cstr(c"."))- match repo_opt {- some repo => {- val status: i32 = checkout.run(repo, rev)- layout.free_repo(repo)- return status- }- none => {- msg.error_prefix()- stdio.eprint("not a veins repository\n", {})- return 1- }- }-}--- a/src/src/cli/diff_cmd.sx+++ /dev/null@@ -1,302 +0,0 @@-/// `vn diff [-r <rev>]`: show a unified diff.--val str = use("std/string")-val stdio = use("std/stdio")-val msg = use("../core/msg.sx")-val bytes = use("../core/bytes.sx")-val lists = use("../core/lists.sx")-val objid = use("../object/id.sx")-val tree = use("../object/tree.sx")-val view = use("../object/view.sx")-val graph = use("../object/graph.sx")-val treediff = use("../object/treediff.sx")-val treewalk = use("../object/treewalk.sx")-val content = use("../object/content.sx")-val store = use("../store/store.sx")-val state = use("../store/state.sx")-val layout = use("../store/layout.sx")-val viewops = use("../store/viewops.sx")-val files = use("../io/files.sx")-val object = use("../git/object.sx")-val snapshot = use("../worktree/snapshot.sx")--type DiffOp = {- tag: mut u8- ai: mut usize- bi: mut usize-}--pub type GitSource = {- repo: mut object.GitRepo- open: mut bool-}--pub fn open_git(repo: layout.Repo) GitSource = trust {- val p: str.StringView = layout.git_dir(repo)- val r = object.open(p)- files.free_path(p)- val g: mut GitSource = GitSource{repo: @zeroed, open: false}- match r {- ok x => {- g.repo = x- g.open = true- }- err _ => {- }- }- return g-}--pub fn close_git(g: mut GitSource) void = trust {- if g.open {- object.free(g.repo)- g.open = false- }-}--fn contains_nul(data: bytes.Bytes) bool = trust {- val n: usize = data.len- val limit: usize = 8192- val i: mut usize = 0- for i < n && i < limit {- if bytes.Bytes.at(data, i) == 0 {- return true- }- i++- }- return false-}--fn split_lines(data: bytes.Bytes) list[bytes.Bytes] = trust {- val out: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()- if data.len == 0 {- return out- }- val start: mut usize = 0- val i: mut usize = 0- for i <= data.len {- val at_end: bool = i == data.len- if at_end || bytes.Bytes.at(data, i) == 10 {- if i > start || !at_end || bytes.Bytes.at(data, i - 1) != 10 {- @append(out, bytes.Bytes.slice(data, start, i))- }- start = i + 1- }- i++- }- return out-}--fn render_one(- handles: list[ref store.Handle],- git: ref GitSource,- change: ref treediff.Change-) void = trust {- val path_view = str.view(change.path.ptr, change.path.len as i64)- if change.new_kind == tree.KIND_CONFLICT {- stdio.print("Conflict: {s}\n", {path_view})- return- }- val old_data: mut bytes.Bytes = bytes.empty()- val new_data: mut bytes.Bytes = bytes.empty()- val old_owned: mut bool = false- val new_owned: mut bool = false- if change.old_kind != treewalk.KIND_MISSING {- val o = content.read_blob(handles, change.old_id, git.repo, git.open)- if o is some d {- old_data = d- old_owned = true- }- }- if change.new_kind != treewalk.KIND_MISSING {- val n = content.read_blob(handles, change.new_id, git.repo, git.open)- if n is some d {- new_data = d- new_owned = true- }- }- if contains_nul(old_data) || contains_nul(new_data) {- stdio.print("Binary files a/{s} and b/{s} differ\n", {path_view, path_view})- } else {- stdio.print("--- ", {})- if change.old_kind == treewalk.KIND_MISSING {- stdio.print("/dev/null", {})- } else {- stdio.print("a/{s}", {path_view})- }- stdio.print("\n+++ ", {})- if change.new_kind == treewalk.KIND_MISSING {- stdio.print("/dev/null", {})- } else {- stdio.print("b/{s}", {path_view})- }- stdio.print("\n", {})- val a = split_lines(old_data)- val b = split_lines(new_data)- val a_count: usize = @len(a)- val b_count: usize = @len(b)- val a_start: mut usize = 1- if a_count == 0 {- a_start = 0- }- val b_start: mut usize = 1- if b_count == 0 {- b_start = 0- }- stdio.print("@@ -{d},{d} +{d},{d} @@\n", {a_start, a_count, b_start, b_count})- val ai: mut usize = 0- for ai < a_count {- val line = line_at(a, ai)- stdio.print("-{s}\n", {str.view(line.ptr, line.len as i64)})- ai++- }- val bi: mut usize = 0- for bi < b_count {- val line2 = line_at(b, bi)- stdio.print("+{s}\n", {str.view(line2.ptr, line2.len as i64)})- bi++- }- @listfree(a)- @listfree(b)- }- if old_owned {- files.free_buffer(old_data)- }- if new_owned {- files.free_buffer(new_data)- }-}--pub fn render(- handles: list[ref store.Handle],- git: mut GitSource,- old_tree: option[objid.Id],- new_tree: option[objid.Id]-) void = trust {- val changes = treediff.compare(handles, old_tree, new_tree)- for c in changes {- render_one(handles, git, c)- }- treediff.free(changes)-}--fn list_bytes(xs: list[bytes.Bytes], i: usize) bytes.Bytes = trust {- val o = @get(xs, i)- if o is some b {- return b- }- return bytes.empty()-}--fn tree_of(handles: list[ref store.Handle], id: objid.Id) option[objid.Id] = trust {- val lc_opt = graph.load_commit(handles, id)- val out: mut option[objid.Id] = none- if lc_opt is some lc {- out = some(graph.copy_id(lc.c.root_tree))- graph.free_loaded(lc)- }- return out-}--fn parent_tree_of(handles: list[ref store.Handle], id: objid.Id) option[objid.Id] = trust {- val lc_opt = graph.load_commit(handles, id)- val out: mut option[objid.Id] = none- if lc_opt is some lc {- if @len(lc.c.parents) > 0 {- val p = @get(lc.c.parents, 0)- if p is some pid {- val t = tree_of(handles, pid)- if t is some tid {- out = some(tid)- }- }- }- graph.free_loaded(lc)- }- return out-}--fn free_tree_opt(t: option[objid.Id]) void = trust {- if t is some id {- if id.ptr != none {- val p: mut ref void = id.ptr as ref void- @free(p)- }- }-}--pub fn run(repo: layout.Repo, revs: list[bytes.Bytes]) i32 = trust {- val snap: i32 = snapshot.run(repo)- if snap != 0 {- return snap- }- val st: store.Store = store.open_all(repo)- val v_opt = state.current_view(repo, st.handles)- val v: mut ref view.View = none- match v_opt {- some x => {- v = x- }- none => {- store.close(st)- msg.error_prefix()- stdio.eprint("no operation state\n", {})- return 1- }- }- val old_tree: mut option[objid.Id] = none- val new_tree: mut option[objid.Id] = none- val status: mut i32 = 0- if @len(revs) >= 2 {- val a: bytes.Bytes = list_bytes(revs, 0)- val b: bytes.Bytes = list_bytes(revs, 1)- val ra = graph.resolve(st.handles, v, a)- val rb = graph.resolve(st.handles, v, b)- if ra is some ia {- old_tree = tree_of(st.handles, ia)- } else {- status = 1- }- if rb is some ib {- new_tree = tree_of(st.handles, ib)- } else {- status = 1- }- } elif @len(revs) == 1 {- val a: bytes.Bytes = list_bytes(revs, 0)- val ra = graph.resolve(st.handles, v, a)- if ra is some ia {- old_tree = parent_tree_of(st.handles, ia)- new_tree = tree_of(st.handles, ia)- } else {- status = 1- }- } else {- val wc_opt = viewops.working_copy(v)- if wc_opt is some wc {- old_tree = parent_tree_of(st.handles, wc)- new_tree = tree_of(st.handles, wc)- }- }- if status != 0 {- msg.error_prefix()- stdio.eprint("unknown revision\n", {})- } else {- val git: mut GitSource = open_git(repo)- render(st.handles, git, old_tree, new_tree)- close_git(git)- }- free_tree_opt(old_tree)- free_tree_opt(new_tree)- view.free_view(v)- store.close(st)- return status-}--fn line_at(ls: list[bytes.Bytes], i: usize) bytes.Bytes = {- val o = @get(ls, i)- if o is some l {- return l- }- return bytes.empty()-}--- a/src/src/cli/fsck_cmd.sx+++ /dev/null@@ -1,23 +0,0 @@-/// `vn fsck`: verify the repository.--val str = use("std/string")-val stdio = use("std/stdio")-val msg = use("../core/msg.sx")-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 => {- msg.error_prefix()- stdio.eprint("not a veins repository: {s}\n", {path})- }- }- return status-}--- a/src/src/cli/git_cmd.sx+++ /dev/null@@ -1,123 +0,0 @@-/// `vn git`: the git bridge. M1 provides `import`.--val str = use("std/string")-val bytes = use("../core/bytes.sx")-val stdio = use("std/stdio")-val msg = use("../core/msg.sx")-val layout = use("../store/layout.sx")-val mirror = use("../git/mirror.sx")-val import = use("../git/import.sx")-val export = use("../git/export.sx")--pub fn run(args: list[ref u8], start: usize) i32 = trust {- val sub_opt = @get(args, start)- val sub: mut ref u8 = none- match sub_opt {- some s => {- sub = s- }- none => {- msg.error_prefix()- stdio.eprint("expected a git subcommand (import)\n", {})- return 1- }- }- if @strcmp(sub, c"import") == 0 {- return run_import(args, start + 1)- }- if @strcmp(sub, c"export") == 0 {- return run_export(args, start + 1)- }- msg.error_prefix()- stdio.eprint("unknown git subcommand: {s}\n", {str.from_cstr(sub)})- return 1-}--fn run_import(args: list[ref u8], start: usize) i32 = trust {- val repo_path: mut str.StringView = str.from_cstr(c".")- val source: mut option[str.StringView] = none- val i: mut usize = start- for i < @len(args) {- val arg_opt = @get(args, i)- if arg_opt is some a {- val av: bytes.Bytes = bytes.from_cstr(a)- val prefix: bytes.Bytes = bytes.bytes(c"-source:", 8)- if bytes.Bytes.starts_with(av, prefix) {- if av.len == 8 {- msg.error_prefix()- stdio.eprint("-source: requires a path\n", {})- return 1- }- val value: bytes.Bytes = bytes.Bytes.slice(av, 8, av.len)- source = some str.view(value.ptr, value.len as i64)- } elif av.len > 0 && bytes.Bytes.at(av, 0) == 45 {- msg.error_prefix()- stdio.eprint("unknown flag: {s}\n", {str.from_cstr(a)})- return 1- } else {- repo_path = str.from_cstr(a)- }- i++- } else {- i++- }- }- val repo_opt = layout.discover(repo_path)- val repo: mut layout.Repo = layout.Repo{root: @zeroed}- match repo_opt {- some r => {- repo = r- }- none => {- msg.error_prefix()- stdio.eprint("not a veins repository: {s}\n", {repo_path})- return 1- }- }- if source is some src {- val prepared = mirror.prepare(repo, src)- if prepared != 0 {- msg.error_prefix()- stdio.eprint("cannot prepare git mirror (code {d})\n", {prepared})- layout.free_repo(repo)- return 1- }- }- val status: i32 = import.run(repo)- layout.free_repo(repo)- return status-}---fn run_export(args: list[ref u8], start: usize) i32 = trust {- val repo_path: mut str.StringView = str.from_cstr(c".")- val i: mut usize = start- for i < @len(args) {- val arg_opt = @get(args, i)- if arg_opt is some a {- val av: bytes.Bytes = bytes.from_cstr(a)- if av.len > 0 && bytes.Bytes.at(av, 0) == 45 {- msg.error_prefix()- stdio.eprint("unknown flag: {s}\n", {str.from_cstr(a)})- return 1- }- repo_path = str.from_cstr(a)- }- i++- }- val repo_opt = layout.discover(repo_path)- val repo: mut layout.Repo = layout.Repo{root: @zeroed}- match repo_opt {- some r => {- repo = r- }- none => {- msg.error_prefix()- stdio.eprint("not a veins repository: {s}\n", {repo_path})- return 1- }- }- val status: i32 = export.run(repo)- layout.free_repo(repo)- return status-}--- a/src/src/cli/help_cmd.sx+++ /dev/null@@ -1,279 +0,0 @@-/// `vn help`: show usage for the program or one of its commands.--val str = use("std/string")-val stdio = use("std/stdio")-val msg = use("../core/msg.sx")--fn cmd_is(a: ref u8, text: ref u8, len: usize) bool = trust {- return str.eql(str.from_cstr(a), str.view(text, len as i64))-}--pub fn usage() void = trust {- stdio.puts("veins is a tool for managing source code")- stdio.puts("")- stdio.puts("commands:")- stdio.puts(" init create a repository")- stdio.puts(" git import from or export to git")- stdio.puts(" checkout write a revision into the working directory")- stdio.puts(" status show working-copy changes")- stdio.puts(" log show commit history")- stdio.puts(" diff show a unified diff")- stdio.puts(" new start a new change")- stdio.puts(" describe set the working-copy commit message")- stdio.puts(" commit describe and start a new change")- stdio.puts(" undo restore the previous operation view")- stdio.puts(" op operation log commands")- stdio.puts(" fsck verify repository integrity")- stdio.puts(" self-test run the format self-tests")- stdio.puts(" version print version information")- stdio.puts(" bench-import compare lazy import metadata; requires git")- stdio.puts(" help show help for a command")- stdio.puts("")- stdio.puts("run 'vn help <command>' for details")-}--fn show_init() void = trust {- stdio.puts("usage: vn init [path] [-git-import:<gitdir>]")- stdio.puts("")- stdio.puts("create a veins repository, optionally importing an existing git repository")- stdio.puts("")- stdio.puts("arguments:")- stdio.puts(" [path] directory to create (default: .)")- stdio.puts("")- stdio.puts("options:")- stdio.puts(" -git-import:<gitdir> import reachable commits and refs from <gitdir>")-}--fn show_git() void = trust {- stdio.puts("usage: vn git <subcommand> [arguments]")- stdio.puts("")- stdio.puts("git bridge commands:")- stdio.puts(" import [-source:<gitdir>] [path]")- stdio.puts(" import reachable git commits and refs")- stdio.puts(" export [path] export commits into the git mirror")- stdio.puts("")- stdio.puts("run 'vn help git <subcommand>' for details")-}--fn show_git_import() void = trust {- stdio.puts("usage: vn git import [-source:<gitdir>] [path]")- stdio.puts("")- stdio.puts("import commits and refs reachable from a git repository")- stdio.puts("")- stdio.puts("arguments:")- stdio.puts(" [path] veins repository (default: .)")- stdio.puts("")- stdio.puts("options:")- stdio.puts(" -source:<gitdir> prepare the mirror from <gitdir> before importing")-}--fn show_checkout() void = trust {- stdio.puts("usage: vn checkout [rev]")- stdio.puts("")- stdio.puts("write a revision into the working directory")- stdio.puts("")- stdio.puts("arguments:")- stdio.puts(" [rev] revision to check out")-}--fn show_fsck() void = trust {- stdio.puts("usage: vn fsck [path] [-verbose]")- stdio.puts("")- stdio.puts("verify pack, index, object, and operation-log integrity")- stdio.puts("")- stdio.puts("arguments:")- stdio.puts(" [path] repository to check (default: .)")- stdio.puts("")- stdio.puts("options:")- stdio.puts(" -v, -verbose print verbose output")-}--fn show_selftest() void = trust {- stdio.puts("usage: vn self-test")- stdio.puts("")- stdio.puts("run the format self-tests")-}--fn show_bench_import() void = trust {- stdio.puts("usage: vn bench-import <gitdir>")- stdio.puts("")- stdio.puts("run the lazy-import metadata pass using the git CLI backend")- stdio.puts("and print commit, tree, entry, and lazy-blob counts")-}--fn show_version() void = trust {- stdio.puts("usage: vn version")- stdio.puts("")- stdio.puts("print version information")-}--fn show_status() void = trust {- stdio.puts("usage: vn status")- stdio.puts("")- stdio.puts("show working-copy changes relative to the parent commit")-}--fn show_log() void = trust {- stdio.puts("usage: vn log [-rev <revset>] [-no-col-titles]")- stdio.puts("")- stdio.puts("show commit history, newest first")- stdio.puts("")- stdio.puts("options:")- stdio.puts(" -rev <revset> show only the given revision set")- stdio.puts(" -no-col-titles omit column titles")-}--fn show_diff() void = trust {- stdio.puts("usage: vn diff [-rev <rev>] [<rev> <rev>]")- stdio.puts("")- stdio.puts("show a unified diff")-}--fn show_new() void = trust {- stdio.puts("usage: vn new [<rev>...]")- stdio.puts("")- stdio.puts("start a new empty change on top of the working copy or a revision")-}--fn show_describe() void = trust {- stdio.puts("usage: vn describe [-message <message>] [<message>]")- stdio.puts("")- stdio.puts("set the working-copy commit message")-}--fn show_commit() void = trust {- stdio.puts("usage: vn commit -message <message>")- stdio.puts("")- stdio.puts("set the message and start a new change")-}--fn show_undo() void = trust {- stdio.puts("usage: vn undo")- stdio.puts("")- stdio.puts("record an operation that restores the previous operation view")-}--fn show_op() void = trust {- stdio.puts("usage: vn op <log|restore|revert> [<op>]")- stdio.puts("")- stdio.puts("inspect and restore operations")-}--fn show_git_export() void = trust {- stdio.puts("usage: vn git export [path]")- stdio.puts("")- stdio.puts("export commits reachable from bookmarks and tags into .veins/git")-}--fn show_help() void = trust {- stdio.puts("usage: vn help [command]")- stdio.puts("")- stdio.puts("show help for the program or a command")- stdio.puts("")- stdio.puts("arguments:")- stdio.puts(" [command] command to describe")-}--pub fn run(args: list[ref u8], start: usize) i32 = trust {- if start >= @len(args) {- usage()- return 0- }- val cmd_opt = @get(args, start)- val cmd: mut ref u8 = none- match cmd_opt {- some c => {- cmd = c- }- none => {- usage()- return 0- }- }-- if cmd_is(cmd, c"init", 4) {- show_init()- return 0- }- if cmd_is(cmd, c"status", 6) {- show_status()- return 0- }- if cmd_is(cmd, c"log", 3) {- show_log()- return 0- }- if cmd_is(cmd, c"diff", 4) {- show_diff()- return 0- }- if cmd_is(cmd, c"new", 3) {- show_new()- return 0- }- if cmd_is(cmd, c"describe", 8) {- show_describe()- return 0- }- if cmd_is(cmd, c"commit", 6) {- show_commit()- return 0- }- if cmd_is(cmd, c"undo", 4) {- show_undo()- return 0- }- if cmd_is(cmd, c"op", 2) {- show_op()- return 0- }- if cmd_is(cmd, c"git", 3) {- if start + 1 < @len(args) {- val sub_opt = @get(args, start + 1)- if sub_opt is some sub {- if cmd_is(sub, c"import", 6) {- show_git_import()- return 0- }- if cmd_is(sub, c"export", 6) {- show_git_export()- return 0- }- msg.error_prefix()- stdio.eprint("unknown git subcommand: {s}\n", {str.from_cstr(sub)})- return 1- }- }- show_git()- return 0- }- if cmd_is(cmd, c"checkout", 8) {- show_checkout()- return 0- }- if cmd_is(cmd, c"fsck", 4) {- show_fsck()- return 0- }- if cmd_is(cmd, c"self-test", 9) {- show_selftest()- return 0- }- if cmd_is(cmd, c"version", 7) {- show_version()- return 0- }- if cmd_is(cmd, c"bench-import", 12) {- show_bench_import()- return 0- }- if cmd_is(cmd, c"help", 4) {- show_help()- return 0- }-- msg.error_prefix()- stdio.eprint("unknown command: {s}\n", {str.from_cstr(cmd)})- usage()- return 1-}--- a/src/src/cli/init_cmd.sx+++ /dev/null@@ -1,38 +0,0 @@-/// `vn init`: create the on-disk repository skeleton and optionally import git.--val str = use("std/string")-val stdio = use("std/stdio")-val msg = use("../core/msg.sx")-val layout = use("../store/layout.sx")-val mirror = use("../git/mirror.sx")-val import = use("../git/import.sx")--pub fn run(path: str.StringView, source: option[str.StringView]) i32 = trust {- val result = layout.init(path)- match result {- ok repo => {- msg.info_prefix()- stdio.print("initialized veins repository at {s}\n", {layout.root_view(repo)})- val mut_source = source- if mut_source is some src {- val prepared: i32 = mirror.prepare(repo, src)- if prepared != 0 {- msg.error_prefix()- stdio.eprint("cannot prepare git mirror (code {d})\n", {prepared})- layout.free_repo(repo)- return 1- }- val status: i32 = import.run(repo)- layout.free_repo(repo)- return status- }- layout.free_repo(repo)- return 0- }- err code => {- msg.error_prefix()- stdio.eprint("init failed with code {d}\n", {code})- return 1- }- }-}--- a/src/src/cli/log_cmd.sx+++ /dev/null@@ -1,372 +0,0 @@-/// `vn log [-rev <revset>]`: show commit history, newest first.--val str = use("std/string")-val stdio = use("std/stdio")-val msg = use("../core/msg.sx")-val terminal = use("std/terminal")-val bytes = use("../core/bytes.sx")-val lists = use("../core/lists.sx")-val objid = use("../object/id.sx")-val view = use("../object/view.sx")-val graph = use("../object/graph.sx")-val changeid = use("../object/changeid.sx")-val treewalk = use("../object/treewalk.sx")-val datetime = use("../core/datetime.sx")-val store = use("../store/store.sx")-val state = use("../store/state.sx")-val layout = use("../store/layout.sx")-val viewops = use("../store/viewops.sx")-val snapshot = use("../worktree/snapshot.sx")--type LogRec = {- id: mut objid.Id- cid: mut bytes.Bytes- seconds: mut i64- tree: mut objid.Id- message: mut bytes.Bytes- author: mut bytes.Bytes- conflicted: mut bool- has_changes: mut bool-}--fn new_rec(- id: objid.Id,- cid: bytes.Bytes,- seconds: i64,- tree_id: objid.Id,- message: bytes.Bytes,- author: bytes.Bytes-) ref LogRec = trust {- val r: mut ref LogRec = @alloc(@sizeof(LogRec)) as ref LogRec- r.id = graph.copy_id(id)- r.cid = bytes.Bytes.dup(cid)- r.seconds = seconds- r.tree = graph.copy_id(tree_id)- r.message = bytes.Bytes.dup(message)- r.author = bytes.Bytes.dup(author)- r.conflicted = false- r.has_changes = false- return r-}--fn free_recs(rs: list[ref LogRec]) void = trust {- for r in rs {- if r.id.ptr != none {- val p: mut ref void = r.id.ptr as ref void- @free(p)- }- if r.cid.ptr != none {- val p2: mut ref void = r.cid.ptr as ref void- @free(p2)- }- if r.tree.ptr != none {- val p3: mut ref void = r.tree.ptr as ref void- @free(p3)- }- if r.message.ptr != none {- val p4: mut ref void = r.message.ptr as ref void- @free(p4)- }- if r.author.ptr != none {- val p5: mut ref void = r.author.ptr as ref void- @free(p5)- }- val rp: mut ref void = r as ref void- @free(rp)- }- @listfree(rs)-}--fn rec_at(rs: list[ref LogRec], i: usize) ref LogRec = trust {- val o = @get(rs, i)- if o is some r {- return r- }- assert false- return none-}--fn sort_recs(rs: mut list[ref LogRec]) void = trust {- val i: mut usize = 1- for i < @len(rs) {- val cur = @get(rs, i)- val c: mut ref LogRec = none- if cur is some v {- c = v- }- val j: mut usize = i- for j > 0 {- val prev_opt = @get(rs, j - 1)- val prev: mut ref LogRec = none- if prev_opt is some v2 {- prev = v2- }- if prev.seconds >= c.seconds {- break- }- @set(rs, j, prev)- j--- }- @set(rs, j, c)- i++- }-}--fn first_line(msg: bytes.Bytes) bytes.Bytes = trust {- val i: mut usize = 0- for i < msg.len {- if bytes.Bytes.at(msg, i) == 10 {- return bytes.Bytes.slice(msg, 0, i)- }- i++- }- return msg-}--fn print_cell(- text: str.StringView,- width: usize,- color: terminal.Color,- dim: bool-) void = trust {- if dim {- terminal.print_styled(text, color, terminal.Color.Default, terminal.Style.Dim)- } elif color == terminal.Color.Default {- stdio.print("{s}", {text})- } else {- terminal.print(text, color)- }- val pad: mut i64 = width as i64 - text.len- for pad > 0 {- stdio.print(" ", {})- pad--- }-}--fn print_gap() void = trust {- stdio.print(" ", {})-}--fn short_cid(rs: list[ref LogRec], idx: usize) bytes.Bytes = trust {- val target: ref LogRec = rec_at(rs, idx)- val limit: usize = target.cid.len- val len: mut usize = 4- if len > limit {- len = limit- }- for len < limit {- val prefix: bytes.Bytes = bytes.Bytes.slice(target.cid, 0, len)- val unique: mut bool = true- val j: mut usize = 0- for j < @len(rs) {- if j != idx {- val other: ref LogRec = rec_at(rs, j)- if !bytes.Bytes.eql(other.cid, target.cid) {- if bytes.Bytes.starts_with(other.cid, prefix) {- unique = false- break- }- }- }- j++- }- if unique {- break- }- len++- }- return bytes.Bytes.dup(bytes.Bytes.slice(target.cid, 0, len))-}--pub fn run(repo: layout.Repo, rev: bytes.Bytes, col_titles: bool) i32 = trust {- val snap: i32 = snapshot.run(repo)- if snap != 0 {- return snap- }- val st: store.Store = store.open_all(repo)- val v_opt = state.current_view(repo, st.handles)- val v: mut ref view.View = none- match v_opt {- some x => {- v = x- }- none => {- store.close(st)- msg.error_prefix()- stdio.eprint("no operation state\n", {})- return 1- }- }- val wc_opt = viewops.working_copy(v)- val wc: mut objid.Id = objid.id_none()- if wc_opt is some id {- wc = id- }- val roots: list[objid.Id] = graph.roots(v)- val ids: list[objid.Id] = collect_ids(st.handles, v, roots, rev)- graph.free_ids(roots)- val recs: mut list[ref LogRec] = lists.new[ref LogRec]()- for id in ids {- val lc_opt = graph.load_commit(st.handles, id)- if lc_opt is some lc {- val cid_full: bytes.Bytes = changeid.encode(lc.c.change_id)- val msg: bytes.Bytes = first_line(lc.c.message)- val rec: mut ref LogRec = new_rec(- id,- cid_full,- lc.c.committer.seconds,- lc.c.root_tree,- msg,- lc.c.author.name- )- rec.conflicted = treewalk.conflicted(st.handles, lc.c.root_tree)- if objid.Id.eql(id, wc) {- rec.has_changes = graph.has_changes(st.handles, lc)- }- changeid.free(cid_full)- graph.free_loaded(lc)- @append(recs, rec)- }- }- sort_recs(recs)- val w_commit: usize = 12- val w_change: mut usize = 6- val w_date: usize = 19- val w_author: mut usize = 6- val k: mut usize = 0- for k < @len(recs) {- val r: ref LogRec = rec_at(recs, k)- val cid: bytes.Bytes = short_cid(recs, k)- if cid.len > w_change {- w_change = cid.len- }- changeid.free(cid)- if r.author.len > w_author {- w_author = r.author.len- }- k++- }- if col_titles {- print_cell(str.from_cstr(c""), 1, terminal.Color.Default, false)- stdio.print(" ", {})- print_cell(str.from_cstr(c"Commit"), w_commit, terminal.Color.Default, false)- print_gap()- print_cell(str.from_cstr(c"Change"), w_change, terminal.Color.Default, false)- print_gap()- print_cell(str.from_cstr(c"Date"), w_date, terminal.Color.Default, false)- print_gap()- print_cell(str.from_cstr(c"Author"), w_author, terminal.Color.Default, false)- print_gap()- stdio.print("Message\n", {})- }- val i: mut usize = 0- for i < @len(recs) {- val r: ref LogRec = rec_at(recs, i)- val marker: mut str.StringView = str.from_cstr(c" ")- val marker_color: mut terminal.Color = terminal.Color.Default- if objid.Id.eql(r.id, wc) {- marker = str.from_cstr(c"@")- marker_color = terminal.Color.Red- if r.has_changes {- marker_color = terminal.Color.BrightCyan- }- }- val hex: ref u8 = objid.Id.hex(r.id)- val short: str.StringView = str.view(hex, 12)- val cid: bytes.Bytes = short_cid(recs, i)- val stamp: bytes.Bytes = datetime.format_utc(r.seconds)- val msg_view = str.view(r.message.ptr, r.message.len as i64)- val author_view = str.view(r.author.ptr, r.author.len as i64)- print_cell(marker, 1, marker_color, false)- stdio.print(" ", {})- print_cell(short, w_commit, terminal.Color.Red, false)- print_gap()- print_cell(- str.view(cid.ptr, cid.len as i64),- w_change,- terminal.Color.Red,- false- )- print_gap()- print_cell(- str.view(stamp.ptr, stamp.len as i64),- w_date,- terminal.Color.Cyan,- true- )- print_gap()- print_cell(author_view, w_author, terminal.Color.Cyan, false)- print_gap()- if msg_view.len > 0 {- terminal.print(msg_view, terminal.Color.Green)- } else {- terminal.print(str.from_cstr(c"<unset>"), terminal.Color.BrightBlack)- }- val names = viewops.bookmark_names(v, r.id)- for name in names {- stdio.print(" [{s}]", {str.view(name.ptr, name.len as i64)})- }- @listfree(names)- val tnames = viewops.tag_names(v, r.id)- for name in tnames {- stdio.print(" <{s}>", {str.view(name.ptr, name.len as i64)})- }- @listfree(tnames)- if r.conflicted {- stdio.print(" (conflicted)", {})- }- val divergent: mut bool = false- val j: mut usize = 0- for j < @len(recs) {- if j != i {- val other = rec_at(recs, j)- if bytes.Bytes.eql(other.cid, r.cid) {- divergent = true- break- }- }- j++- }- if divergent {- stdio.print(" (divergent)", {})- }- stdio.print("\n", {})- @free(hex as ref void)- changeid.free(cid)- // timestamp is freed by the arena-style process exit- i++- }- free_recs(recs)- graph.free_ids(ids)- view.free_view(v)- if wc.ptr != none {- val wp: mut ref void = wc.ptr as ref void- @free(wp)- }- store.close(st)- return 0-}--fn collect_ids(- handles: list[ref store.Handle],- v: ref view.View,- roots: list[objid.Id],- rev: bytes.Bytes-) list[objid.Id] = trust {- if rev.len == 0 || bytes.Bytes.eql(rev, bytes.bytes(c"all()", 5)) {- return graph.collect(handles, roots)- }- val resolved = graph.resolve(handles, v, rev)- match resolved {- some id => {- val one: mut list[objid.Id] = lists.new[objid.Id]()- @append(one, graph.copy_id(id))- val out = graph.collect(handles, one)- graph.free_ids(one)- return out- }- none => {- return lists.new[objid.Id]()- }- }-}--- a/src/src/cli/new_cmd.sx+++ /dev/null@@ -1,379 +0,0 @@-/// `vn describe`, `vn new`, and `vn commit`.--val stdio = use("std/stdio")-val msg = use("../core/msg.sx")-val bytes = use("../core/bytes.sx")-val buf = use("../core/buf.sx")-val lists = use("../core/lists.sx")-val prim = use("../core/primitives.sx")-val random = use("std/crypto/random")-val objid = use("../object/id.sx")-val types = use("../object/types.sx")-val commit = use("../object/commit.sx")-val graph = use("../object/graph.sx")-val store = use("../store/store.sx")-val layout = use("../store/layout.sx")-val txn = use("../store/txn.sx")-val viewops = use("../store/viewops.sx")-val identity = use("../core/identity.sx")-val gitmap = use("../git/map.sx")-val snapshot = use("../worktree/snapshot.sx")-val checkout = use("../worktree/checkout.sx")--val NOTHING_TO_COMMIT: i32 = 2--fn copy_id(id: objid.Id) objid.Id = trust {- val out: ref u8 = @alloc(32) as ref u8- @memcpy(out as ref void, id.ptr as ref void, 32)- return objid.id(out)-}--fn copy_renames(rs: list[ref commit.Rename]) list[ref commit.Rename] = trust {- val out: mut list[ref commit.Rename] = lists.new[ref commit.Rename]()- for r in rs {- @append(- out,- commit.new_rename(- r.parent_index,- r.kind,- bytes.Bytes.dup(r.from_path),- bytes.Bytes.dup(r.to_path)- )- )- }- return out-}--fn copy_kvs(xs: list[ref prim.KeyValue]) list[ref prim.KeyValue] = trust {- val out: mut list[ref prim.KeyValue] = lists.new[ref prim.KeyValue]()- for kv in xs {- @append(out, commit.new_kv(bytes.Bytes.dup(kv.key), bytes.Bytes.dup(kv.value)))- }- return out-}--fn free_renames(rs: list[ref commit.Rename]) void = trust {- for r in rs {- if r.from_path.ptr != none {- val fp: mut ref void = r.from_path.ptr as ref void- @free(fp)- }- if r.to_path.ptr != none {- val tp: mut ref void = r.to_path.ptr as ref void- @free(tp)- }- val rp: mut ref void = r as ref void- @free(rp)- }- @listfree(rs)-}--fn free_kvs(xs: list[ref prim.KeyValue]) void = trust {- for kv in xs {- if kv.key.ptr != none {- val kp: mut ref void = kv.key.ptr as ref void- @free(kp)- }- if kv.value.ptr != none {- val vp: mut ref void = kv.value.ptr as ref void- @free(vp)- }- val xp: mut ref void = kv as ref void- @free(xp)- }- @listfree(xs)-}--fn join_args(args: list[bytes.Bytes]) bytes.Bytes = trust {- val b: mut buf.Buf = buf.new(64)- val i: mut usize = 0- for i < @len(args) {- if i > 0 {- buf.Buf.put_u8(b, 32)- }- val o = @get(args, i)- if o is some v {- buf.Buf.put_bytes(b, v)- }- i++- }- val out: bytes.Bytes = bytes.Bytes.dup(buf.Buf.view(b))- buf.Buf.free(b)- return out-}--fn describe_impl(repo: layout.Repo, args: list[bytes.Bytes], require_changes: bool) i32 = trust {- val snap: i32 = snapshot.run(repo)- if snap != 0 {- return snap- }- val message: bytes.Bytes = join_args(args)- val tx_opt = txn.begin(repo)- val tx: mut ref txn.Txn = none- match tx_opt {- some t => {- tx = t- }- none => {- msg.error_prefix()- stdio.eprint("cannot load repository state\n", {})- val mp: mut ref void = message.ptr as ref void- @free(mp)- return 1- }- }- val wc_opt = viewops.working_copy(tx.view)- val wc: mut objid.Id = objid.id_none()- val have_wc: mut bool = false- if wc_opt is some id {- wc = id- have_wc = true- }- if !have_wc {- msg.error_prefix()- stdio.eprint("no working-copy commit\n", {})- txn.abort(tx)- val mp2: mut ref void = message.ptr as ref void- @free(mp2)- return 1- }- val st: store.Store = store.open_all(repo)- val lc_opt = graph.load_commit(st.handles, wc)- if lc_opt is none {- msg.error_prefix()- stdio.eprint("cannot read working-copy commit\n", {})- store.close(st)- txn.abort(tx)- val mp2: mut ref void = message.ptr as ref void- @free(mp2)- return 1- }- val lc: mut ref graph.LoadedCommit = none- if lc_opt is some x {- lc = x- }- val changed: bool = graph.has_changes(st.handles, lc)- val same_message: bool = bytes.Bytes.eql(message, lc.c.message)- if !changed && (require_changes || same_message) {- if require_changes {- msg.info_prefix()- stdio.print("nothing to commit, working copy clean\n", {})- }- store.close(st)- txn.abort(tx)- graph.free_loaded(lc)- val mp: mut ref void = message.ptr as ref void- @free(mp)- if wc.ptr != none {- val wp: mut ref void = wc.ptr as ref void- @free(wp)- }- if require_changes {- return NOTHING_TO_COMMIT- }- return 0- }- val sig = identity.signature(repo)- val parents: mut list[objid.Id] = lists.new[objid.Id]()- for p in lc.c.parents {- @append(parents, copy_id(p))- }- val renames: list[ref commit.Rename] = copy_renames(lc.c.renames)- val extra: list[ref prim.KeyValue] = copy_kvs(lc.c.extra)- val nc: mut ref commit.Commit = @alloc(@sizeof(commit.Commit)) as ref commit.Commit- nc.version = 1- nc.parents = parents- nc.root_tree = copy_id(lc.c.root_tree)- nc.change_id = lc.c.change_id- nc.author = lc.c.author- nc.committer = sig- nc.message = message- nc.renames_state = lc.c.renames_state- nc.renames = renames- nc.extra = extra- val encoded: bytes.Bytes = commit.encode(nc)- val new_id: objid.Id = txn.add_object(tx, types.COMMIT, encoded)- viewops.remove_head(tx.view, wc)- viewops.set_workspace(tx.view, new_id)- viewops.rebuild_heads(tx.view)- val status: i32 = txn.finish(tx, bytes.bytes(c"describe", 8))- if status == 0 {- val _ = gitmap.mark_native(repo, new_id)- }- store.close(st)- graph.free_loaded(lc)- @listfree(parents)- free_renames(renames)- free_kvs(extra)- @free(nc.root_tree.ptr as ref void)- @free(nc as ref void)- val mp3: mut ref void = message.ptr as ref void- @free(mp3)- val nip: mut ref void = new_id.ptr as ref void- @free(nip)- if wc.ptr != none {- val wp: mut ref void = wc.ptr as ref void- @free(wp)- }- identity.free_sig(sig)- return status-}--pub fn describe(repo: layout.Repo, args: list[bytes.Bytes]) i32 = trust {- return describe_impl(repo, args, false)-}--pub fn commit_changes(repo: layout.Repo, args: list[bytes.Bytes]) i32 = trust {- val d: i32 = describe_impl(repo, args, true)- if d == NOTHING_TO_COMMIT {- return 0- }- if d != 0 {- return d- }- val empty: list[bytes.Bytes] = lists.new[bytes.Bytes]()- val status: i32 = new_change(repo, empty)- @listfree(empty)- return status-}--pub fn new_change(repo: layout.Repo, revs: list[bytes.Bytes]) i32 = trust {- val snap: i32 = snapshot.run(repo)- if snap != 0 {- return snap- }- val tx_opt = txn.begin(repo)- val tx: mut ref txn.Txn = none- match tx_opt {- some t => {- tx = t- }- none => {- msg.error_prefix()- stdio.eprint("cannot load repository state\n", {})- return 1- }- }- val st: store.Store = store.open_all(repo)- val wc_opt = viewops.working_copy(tx.view)- val wc: mut objid.Id = objid.id_none()- val have_wc: mut bool = false- if wc_opt is some id {- wc = id- have_wc = true- }- val parents: mut list[objid.Id] = lists.new[objid.Id]()- val root_tree: mut objid.Id = objid.id_none()- if @len(revs) == 0 {- if !have_wc {- msg.error_prefix()- stdio.eprint("no working-copy commit\n", {})- store.close(st)- txn.abort(tx)- return 1- }- val lc_opt = graph.load_commit(st.handles, wc)- match lc_opt {- some lc => {- @append(parents, copy_id(wc))- root_tree = copy_id(lc.c.root_tree)- graph.free_loaded(lc)- }- none => {- msg.error_prefix()- stdio.eprint("cannot read working-copy commit\n", {})- store.close(st)- txn.abort(tx)- return 1- }- }- } else {- val i: mut usize = 0- val mut_failed: mut bool = false- for i < @len(revs) {- val r = @get(revs, i)- val rev: mut bytes.Bytes = bytes.empty()- if r is some v {- rev = v- }- val resolved = graph.resolve(st.handles, tx.view, rev)- match resolved {- some id => {- @append(parents, copy_id(id))- if i == 0 {- val lc_opt = graph.load_commit(st.handles, id)- match lc_opt {- some lc => {- root_tree = copy_id(lc.c.root_tree)- graph.free_loaded(lc)- }- none => {- mut_failed = true- }- }- }- }- none => {- mut_failed = true- }- }- i++- }- if mut_failed {- msg.error_prefix()- stdio.eprint("unknown revision\n", {})- store.close(st)- txn.abort(tx)- graph.free_ids(parents)- return 1- }- }- val cid: ref u8 = @alloc(16) as ref u8- random.random_bytes(cid as ref void, 16)- val sig = identity.signature(repo)- val renames: list[ref commit.Rename] = lists.new[ref commit.Rename]()- val extra: list[ref prim.KeyValue] = lists.new[ref prim.KeyValue]()- val nc: mut ref commit.Commit = @alloc(@sizeof(commit.Commit)) as ref commit.Commit- nc.version = 1- nc.parents = parents- nc.root_tree = root_tree- nc.change_id = objid.change_id(cid)- nc.author = sig- nc.committer = sig- nc.message = bytes.empty()- nc.renames_state = commit.RENAMES_RECORDED- nc.renames = renames- nc.extra = extra- val encoded: bytes.Bytes = commit.encode(nc)- val new_id: objid.Id = txn.add_object(tx, types.COMMIT, encoded)- if have_wc {- viewops.remove_head(tx.view, wc)- }- viewops.set_workspace(tx.view, new_id)- viewops.rebuild_heads(tx.view)- val status: i32 = txn.finish(tx, bytes.bytes(c"new", 3))- if status == 0 {- val _ = gitmap.mark_native(repo, new_id)- }- store.close(st)- @listfree(parents)- @listfree(renames)- @listfree(extra)- @free(root_tree.ptr as ref void)- @free(nc as ref void)- @free(cid as ref void)- val nip: mut ref void = new_id.ptr as ref void- @free(nip)- if wc.ptr != none {- val wp: mut ref void = wc.ptr as ref void- @free(wp)- }- identity.free_sig(sig)- if status != 0 {- return status- }- if @len(revs) > 0 {- return checkout.run(repo, bytes.empty())- }- return 0-}--- a/src/src/cli/op_cmd.sx+++ /dev/null@@ -1,330 +0,0 @@-/// Operation log commands: `op log`, `op restore`, `op revert`, and `undo`.--val str = use("std/string")-val stdio = use("std/stdio")-val msg = use("../core/msg.sx")-val bytes = use("../core/bytes.sx")-val lists = use("../core/lists.sx")-val objid = use("../object/id.sx")-val operation = use("../object/operation.sx")-val view = use("../object/view.sx")-val datetime = use("../core/datetime.sx")-val store = use("../store/store.sx")-val state = use("../store/state.sx")-val layout = use("../store/layout.sx")-val txn = use("../store/txn.sx")--type OpRec = {- id: mut objid.Id- op: mut ref operation.Operation-}--fn copy_id(id: objid.Id) objid.Id = trust {- val out: ref u8 = @alloc(32) as ref u8- @memcpy(out as ref void, id.ptr as ref void, 32)- return objid.id(out)-}--fn contains(ids: list[objid.Id], id: objid.Id) bool = trust {- for x in ids {- if objid.Id.eql(x, id) {- return true- }- }- return false-}--fn free_ids(ids: list[objid.Id]) void = trust {- for id in ids {- if id.ptr != none {- val p: mut ref void = id.ptr as ref void- @free(p)- }- }- @listfree(ids)-}--fn collect(- handles: list[ref store.Handle],- heads: list[objid.Id]-) list[ref OpRec] = trust {- val out: mut list[ref OpRec] = lists.new[ref OpRec]()- val seen: mut list[objid.Id] = lists.new[objid.Id]()- val stack: mut list[objid.Id] = lists.new[objid.Id]()- for h in heads {- @append(stack, copy_id(h))- }- for @len(stack) > 0 {- val id: objid.Id = @remove(stack, @len(stack) - 1)- if contains(seen, id) {- val ip: mut ref void = id.ptr as ref void- @free(ip)- continue- }- @append(seen, copy_id(id))- val op_opt = state.read_operation(handles, id)- if op_opt is some op {- for p in op.parents {- if !contains(seen, p) {- @append(stack, copy_id(p))- }- }- val rec: mut ref OpRec = @alloc(@sizeof(OpRec)) as ref OpRec- rec.id = id- rec.op = op- @append(out, rec)- }- }- @listfree(stack)- free_ids(seen)- return out-}--fn free_recs(recs: list[ref OpRec]) void = trust {- for r in recs {- operation.free_operation(r.op)- if r.id.ptr != none {- val p: mut ref void = r.id.ptr as ref void- @free(p)- }- val rp: mut ref void = r as ref void- @free(rp)- }- @listfree(recs)-}--fn rec_at(rs: list[ref OpRec], i: usize) ref OpRec = trust {- val o = @get(rs, i)- if o is some r {- return r- }- assert false- return none-}--fn sort_recs(rs: mut list[ref OpRec]) void = trust {- val i: mut usize = 1- for i < @len(rs) {- val cur = @get(rs, i)- val c: mut ref OpRec = none- if cur is some v {- c = v- }- val j: mut usize = i- for j > 0 {- val prev_o = @get(rs, j - 1)- val prev: mut ref OpRec = none- if prev_o is some vv {- prev = vv- }- if prev.op.end.ms >= c.op.end.ms {- break- }- @set(rs, j, prev)- j--- }- @set(rs, j, c)- i++- }-}--fn resolve_op(recs: list[ref OpRec], text: bytes.Bytes) option[objid.Id] = trust {- val matches: mut list[objid.Id] = lists.new[objid.Id]()- val i: mut usize = 0- for i < @len(recs) {- val r = rec_at(recs, i)- val hex: ref u8 = objid.Id.hex(r.id)- val full: bytes.Bytes = bytes.bytes(hex, 64)- val matched: bool = full.len >= text.len && bytes.Bytes.eql(- bytes.Bytes.slice(full, 0, text.len),- text- )- @free(hex as ref void)- if matched {- @append(matches, copy_id(r.id))- }- i++- }- val out: mut option[objid.Id] = none- if @len(matches) == 1 {- val o = @get(matches, 0)- if o is some only {- out = some copy_id(only)- }- }- free_ids(matches)- return out-}--fn find_rec(recs: list[ref OpRec], id: objid.Id) option[ref OpRec] = trust {- for r in recs {- if objid.Id.eql(r.id, id) {- return some r- }- }- return none-}--pub fn log(repo: layout.Repo) i32 = trust {- val st: store.Store = store.open_all(repo)- val heads: list[objid.Id] = state.heads(repo)- val recs: mut list[ref OpRec] = collect(st.handles, heads)- sort_recs(recs)- val i: mut usize = 0- for i < @len(recs) {- val r = rec_at(recs, i)- val hex: ref u8 = objid.Id.hex(r.id)- val stamp: bytes.Bytes = datetime.format_utc(r.op.end.ms / 1000)- val marker: mut str.StringView = str.from_cstr(c" ")- if contains(heads, r.id) {- marker = str.from_cstr(c"@")- }- stdio.print(- "{s} {s} {s} {s}\n",- {- marker,- str.view(hex, 12),- str.view(stamp.ptr, stamp.len as i64),- str.view(r.op.description.ptr, r.op.description.len as i64)- }- )- @free(hex as ref void)- // timestamp is freed by the arena-style process exit- i++- }- free_recs(recs)- free_ids(heads)- store.close(st)- return 0-}--fn write_view(- repo: layout.Repo,- new_view: ref view.View,- description: bytes.Bytes-) i32 = trust {- val tx_opt = txn.begin(repo)- val tx: mut ref txn.Txn = none- match tx_opt {- some t => {- tx = t- }- none => {- msg.error_prefix()- stdio.eprint("cannot load repository state\n", {})- return 1- }- }- view.free_view(tx.view)- tx.view = new_view- val status: i32 = txn.finish(tx, description)- return status-}--pub fn restore(repo: layout.Repo, text: bytes.Bytes) i32 = trust {- val st: store.Store = store.open_all(repo)- val heads: list[objid.Id] = state.heads(repo)- val recs: mut list[ref OpRec] = collect(st.handles, heads)- val target = resolve_op(recs, text)- val status: mut i32 = 1- if target is some tid {- val rec_opt = find_rec(recs, tid)- if rec_opt is some rec {- val target_view = state.read_view(st.handles, rec.op.view)- if target_view is some tv {- status = write_view(repo, tv, bytes.bytes(c"op restore", 10))- } else {- msg.error_prefix()- stdio.eprint("cannot read operation view\n", {})- }- }- } else {- msg.error_prefix()- stdio.eprint("unknown operation\n", {})- }- free_recs(recs)- free_ids(heads)- store.close(st)- return status-}--pub fn revert(repo: layout.Repo, text: bytes.Bytes) i32 = trust {- // A revert of the latest operation restores its parent view. More complex- // three-way inverses are handled by the merge engine in a later milestone.- val st: store.Store = store.open_all(repo)- val heads: list[objid.Id] = state.heads(repo)- val recs: mut list[ref OpRec] = collect(st.handles, heads)- val target = resolve_op(recs, text)- val status: mut i32 = 1- if target is some tid {- val rec_opt = find_rec(recs, tid)- if rec_opt is some rec {- if @len(rec.op.parents) > 0 {- val p = @get(rec.op.parents, 0)- if p is some pid {- val parent_opt = state.read_operation(st.handles, pid)- if parent_opt is some parent {- val pv = state.read_view(st.handles, parent.view)- if pv is some tv {- status = write_view(repo, tv, bytes.bytes(c"op revert", 9))- }- operation.free_operation(parent)- }- }- } else {- val empty: ref view.View = state.empty_view()- status = write_view(repo, empty, bytes.bytes(c"op revert", 9))- }- }- } else {- msg.error_prefix()- stdio.eprint("unknown operation\n", {})- }- free_recs(recs)- free_ids(heads)- store.close(st)- return status-}--pub fn undo(repo: layout.Repo) i32 = trust {- val st: store.Store = store.open_all(repo)- val heads: list[objid.Id] = state.heads(repo)- if @len(heads) == 0 {- msg.error_prefix()- stdio.eprint("no operations to undo\n", {})- store.close(st)- return 1- }- val recs: mut list[ref OpRec] = collect(st.handles, heads)- sort_recs(recs)- val status: mut i32 = 1- if @len(recs) > 0 {- val latest = rec_at(recs, 0)- val target_view: mut option[ref view.View] = none- if @len(latest.op.parents) > 0 {- val p = @get(latest.op.parents, 0)- if p is some pid {- val parent_opt = state.read_operation(st.handles, pid)- if parent_opt is some parent {- target_view = state.read_view(st.handles, parent.view)- operation.free_operation(parent)- }- }- } else {- target_view = some(state.empty_view())- }- match target_view {- some tv => {- status = write_view(repo, tv, bytes.bytes(c"undo", 4))- }- none => {- msg.error_prefix()- stdio.eprint("cannot resolve undo target\n", {})- }- }- }- free_recs(recs)- free_ids(heads)- store.close(st)- return status-}--- a/src/src/cli/selftest_cmd.sx+++ /dev/null@@ -1,553 +0,0 @@-/// 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 msg = use("../core/msg.sx")-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++- }-}--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++- }- fuzz_once(bytes.bytes(data, n))- i++- }- @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"56504b310100000001000000000000008be3caa39b307b2b4a46533174cc7faa49c0ff34317302d188276c9641be35fb030001010072c385a83448a5e16853735a79a212f0377d0e40be777d121271758525dbc911"- )- assert_bytes_hash(- out.index,- c"d5dfb7b2ce4235f87856c12ff2e0b65d817dc29dfedad62ba34e71d74dca0cfc"- )- 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"c83c67617ae4445631508cc4edba83ba58d9e996cea40c980ec69a8b6da86458")- val c1 = objid.object_id(types.CHUNK, bytes.Bytes.slice(bytes.bytes(data, n), 262144, n))- assert_id(c1, c"0c91665d423fd704baae9454d24697460c4898fbf16cc6ad498d3f750d073a4b")- val built: ref blob.BlobBuild = blob.build(data, n)- val root = objid.object_id(types.BLOB, built.root_body)- assert_id(root, c"937fe1a8d674aa28cb9fa074a76ea84cdc1d6c61e209f47bbdebbe4361b698cf")- assert_id(- blob.root_id(built),- c"937fe1a8d674aa28cb9fa074a76ea84cdc1d6c61e209f47bbdebbe4361b698cf"- )- 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++- }- 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"8be3caa39b307b2b4a46533174cc7faa49c0ff34317302d188276c9641be35fb")- val commit_id: objid.Id = make_commit(repo, tree_id)- assert_id(commit_id, c"7f648b3621402df01985d121888c89c37107274fb8bb54661f12deca6cc72299")- val conflict_id: objid.Id = make_conflict(repo)- assert_id(conflict_id, c"02b5ddd6d982a32aa19d1c1b11d09165b44667b0c33acd993c44457dedcabd06")- val view_id: objid.Id = make_view(repo, commit_id)- assert_id(view_id, c"a2e19569bb3b5c28775bc8503c45c4edce6d51f55303e39bc02eec529324cd11")- val op_id: objid.Id = make_operation(repo, view_id)- assert_id(op_id, c"0a5494529353fb5886870a128139e07d95f40afcd831afc423617808f31dc426")- 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/veins-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 => {- msg.error_prefix()- stdio.eprint("self-test: 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 {- msg.error_prefix()- stdio.eprint("self-test: fsck failed\n", {})- return 1- }- msg.info_prefix()- stdio.print("self-test: OK\n", {})- return 0-}--- a/src/src/cli/status_cmd.sx+++ /dev/null@@ -1,124 +0,0 @@-/// `vn status`: show working-copy changes relative to the parent commit.--val stdio = use("std/stdio")-val msg = use("../core/msg.sx")-val str = use("std/string")-val objid = use("../object/id.sx")-val tree = use("../object/tree.sx")-val graph = use("../object/graph.sx")-val treediff = use("../object/treediff.sx")-val treewalk = use("../object/treewalk.sx")-val view = use("../object/view.sx")-val store = use("../store/store.sx")-val state = use("../store/state.sx")-val layout = use("../store/layout.sx")-val viewops = use("../store/viewops.sx")-val snapshot = use("../worktree/snapshot.sx")--fn first_parent_tree(handles: list[ref store.Handle], id: objid.Id) option[objid.Id] = trust {- val lc_opt = graph.load_commit(handles, id)- val out: mut option[objid.Id] = none- if lc_opt is some lc {- if @len(lc.c.parents) > 0 {- val p = @get(lc.c.parents, 0)- if p is some pid {- val pl = graph.load_commit(handles, pid)- if pl is some parent {- out = some(graph.copy_id(parent.c.root_tree))- graph.free_loaded(parent)- }- }- }- graph.free_loaded(lc)- }- return out-}--fn working_tree(handles: list[ref store.Handle], id: objid.Id) option[objid.Id] = trust {- val lc_opt = graph.load_commit(handles, id)- val out: mut option[objid.Id] = none- if lc_opt is some lc {- out = some(graph.copy_id(lc.c.root_tree))- graph.free_loaded(lc)- }- return out-}--pub fn run(repo: layout.Repo) i32 = trust {- val snap: i32 = snapshot.run(repo)- if snap != 0 {- return snap- }- val st: store.Store = store.open_all(repo)- val v_opt = state.current_view(repo, st.handles)- val v: mut ref view = none- match v_opt {- some x => {- v = x- }- none => {- store.close(st)- msg.error_prefix()- stdio.eprint("no operation state\n", {})- return 1- }- }- val wc_opt = viewops.working_copy(v)- val wc: mut objid.Id = objid.id_none()- match wc_opt {- some id => {- wc = id- }- none => {- msg.info_prefix()- stdio.print("working copy clean\n", {})- view.free_view(v)- store.close(st)- return 0- }- }- val new_tree_opt = working_tree(st.handles, wc)- val old_tree_opt = first_parent_tree(st.handles, wc)- val changes = treediff.compare(st.handles, old_tree_opt, new_tree_opt)- val conflicted_count: mut usize = 0- for c in changes {- val path_view = str.view(c.path.ptr, c.path.len as i64)- if c.old_kind == treewalk.KIND_MISSING {- stdio.print("A {s}\n", {path_view})- } elif c.new_kind == treewalk.KIND_MISSING {- stdio.print("D {s}\n", {path_view})- } elif c.new_kind == tree.KIND_CONFLICT {- stdio.print("C {s}\n", {path_view})- conflicted_count++- } else {- stdio.print("M {s}\n", {path_view})- }- }- if @len(changes) == 0 {- msg.info_prefix()- stdio.print("working copy clean\n", {})- }- if conflicted_count > 0 {- stdio.print("{d} conflict(s)\n", {conflicted_count})- }- treediff.free(changes)- view.free_view(v)- if wc.ptr != none {- val wp: mut ref void = wc.ptr as ref void- @free(wp)- }- if new_tree_opt is some nt {- if nt.ptr != none {- val np: mut ref void = nt.ptr as ref void- @free(np)- }- }- if old_tree_opt is some ot {- if ot.ptr != none {- val op: mut ref void = ot.ptr as ref void- @free(op)- }- }- store.close(st)- return 0-}--- a/src/src/core/buf.sx+++ /dev/null@@ -1,164 +0,0 @@-/// 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++-}--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 += 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 += 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)-}--- a/src/src/core/bytes.sx+++ /dev/null@@ -1,141 +0,0 @@-/// 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++- }- 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++- }- 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++- }- return true-}--- a/src/src/core/datetime.sx+++ /dev/null@@ -1,83 +0,0 @@-/// UTC timestamp formatting for log and operation output.--val bytes = use("bytes.sx")-val buf = use("buf.sx")--fn floor_div(a: i64, b: i64) i64 = trust {- val q: i64 = a / b- val r: i64 = a % b- if r != 0 && ((r < 0) != (b < 0)) {- return q - 1- }- return q-}--fn put_pad(b: mut buf.Buf, value: i64, width: usize) void = trust {- val v: mut i64 = value- if v < 0 {- v = 0- }- val tmp: ref u8 = @alloc(24) as ref u8- val n: mut usize = 0- for v > 0 {- @store8(@ptradd(tmp, n as i64), (48 + (v % 10)) as u8)- v = v / 10- n++- }- if n == 0 {- @store8(@ptradd(tmp, 0), 48)- n = 1- }- val pad: usize = width - n- val i: mut usize = 0- for i < pad {- buf.Buf.put_u8(b, 48)- i++- }- val j: mut usize = n- for j > 0 {- j--- buf.Buf.put_u8(b, @load8(@ptradd(tmp, j as i64)))- }- @free(tmp as ref void)-}--pub fn format_utc(seconds: i64) bytes.Bytes = trust {- val days: i64 = floor_div(seconds, 86400)- val rem: i64 = seconds - days * 86400- val hour: i64 = rem / 3600- val minute: i64 = (rem % 3600) / 60- val second: i64 = rem % 60- val z: i64 = days + 719468- val era: i64 = floor_div(z, 146097)- val doe: i64 = z - era * 146097- val yoe: i64 = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365- val y0: i64 = yoe + era * 400- val doy: i64 = doe - (365 * yoe + yoe / 4 - yoe / 100)- val mp: i64 = (5 * doy + 2) / 153- val d: i64 = doy - (153 * mp + 2) / 5 + 1- val m0: i64 = mp + 3- val m: mut i64 = m0- if mp >= 10 {- m = mp - 9- }- val y: mut i64 = y0- if m <= 2 {- y = y + 1- }- val b: mut buf.Buf = buf.new(32)- put_pad(b, y, 4)- buf.Buf.put_u8(b, 45)- put_pad(b, m, 2)- buf.Buf.put_u8(b, 45)- put_pad(b, d, 2)- buf.Buf.put_u8(b, 32)- put_pad(b, hour, 2)- buf.Buf.put_u8(b, 58)- put_pad(b, minute, 2)- buf.Buf.put_u8(b, 58)- put_pad(b, second, 2)- val out: bytes.Bytes = bytes.Bytes.dup(buf.Buf.view(b))- buf.Buf.free(b)- return out-}--- a/src/src/core/error.sx+++ /dev/null@@ -1,85 +0,0 @@-/// 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"-}--- a/src/src/core/identity.sx+++ /dev/null@@ -1,137 +0,0 @@-/// Author/committer identity from the local config or environment.--val str = use("std/string")-val os = use("std/os")-val time = use("std/time")-val bytes = use("../core/bytes.sx")-val prim = use("../core/primitives.sx")-val layout = use("../store/layout.sx")-val files = use("../io/files.sx")--fn trim(b: bytes.Bytes) bytes.Bytes = trust {- val start: mut usize = 0- val end: mut usize = b.len- for start < end {- val c: u8 = bytes.Bytes.at(b, start)- if c != 32 && c != 9 && c != 13 && c != 10 {- break- }- start++- }- for end > start {- val c2: u8 = bytes.Bytes.at(b, end - 1)- if c2 != 32 && c2 != 9 && c2 != 13 && c2 != 10 {- break- }- end--- }- return bytes.Bytes.slice(b, start, end)-}--fn config_value(repo: layout.Repo, key: bytes.Bytes) option[bytes.Bytes] = trust {- val path: str.StringView = layout.config_path(repo)- val data_opt = files.read_all(path)- files.free_path(path)- if data_opt is some data {- val pos: mut usize = 0- val start: mut usize = 0- for pos <= data.len {- val at_end: bool = pos == data.len- if at_end || bytes.Bytes.at(data, pos) == 10 {- val line: bytes.Bytes = trim(bytes.Bytes.slice(data, start, pos))- if line.len > 0 && bytes.Bytes.at(line, 0) != 35 {- val eq: mut i64 = -1- val i: mut usize = 0- for i < line.len {- if bytes.Bytes.at(line, i) == 61 {- if eq < 0 {- eq = i as i64- }- }- i++- }- if eq >= 0 {- val k: bytes.Bytes = trim(bytes.Bytes.slice(line, 0, eq as usize))- if bytes.Bytes.eql(k, key) {- val v: bytes.Bytes = trim(- bytes.Bytes.slice(line, eq as usize + 1, line.len)- )- val out: bytes.Bytes = bytes.Bytes.dup(v)- files.free_buffer(data)- return some out- }- }- }- start = pos + 1- }- pos++- }- files.free_buffer(data)- }- return none-}--fn env_dup(name: ref u8) option[bytes.Bytes] = trust {- val v = os.env(name)- match v {- some s => {- return some bytes.Bytes.dup(bytes.from_cstr(s))- }- none => {- return none- }- }-}--fn first_config(- repo: layout.Repo,- key: bytes.Bytes,- env1: ref u8,- env2: ref u8-) bytes.Bytes = trust {- val c = config_value(repo, key)- if c is some v {- return v- }- val e1 = env_dup(env1)- if e1 is some v {- return v- }- val e2 = env_dup(env2)- if e2 is some v {- return v- }- return bytes.Bytes.dup(bytes.bytes(c"unknown", 7))-}--pub fn signature(repo: layout.Repo) prim.Sig = trust {- val name: bytes.Bytes = first_config(- repo,- bytes.bytes(c"user.name", 9),- c"GIT_AUTHOR_NAME",- c"USER"- )- val email: bytes.Bytes = first_config(- repo,- bytes.bytes(c"user.email", 10),- c"GIT_AUTHOR_EMAIL",- c"EMAIL"- )- return prim.Sig{- name: name,- email: email,- seconds: time.unix_now(),- tz_min: 0- }-}--pub fn free_sig(s: prim.Sig) void = trust {- if s.name.ptr != none {- val np: mut ref void = s.name.ptr as ref void- @free(np)- }- if s.email.ptr != none {- val ep: mut ref void = s.email.ptr as ref void- @free(ep)- }-}--- a/src/src/core/lists.sx+++ /dev/null@@ -1,20 +0,0 @@-/// 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- }- }-}--- a/src/src/core/msg.sx+++ /dev/null@@ -1,27 +0,0 @@-/// User-facing log messages with consistent level prefixes and colors.--val stdio = use("std/stdio")-val terminal = use("std/terminal")--/// Print a red, bold `error:` prefix to stderr.-pub fn error_prefix() void = trust {- terminal.eprint_styled("error", terminal.Color.Red, terminal.Color.Default, terminal.Style.Bold)- stdio.eprint(": ", {})-}--/// Print a yellow, bold `warning:` prefix to stderr.-pub fn warning_prefix() void = trust {- terminal.eprint_styled(- "warning",- terminal.Color.Yellow,- terminal.Color.Default,- terminal.Style.Bold- )- stdio.eprint(": ", {})-}--/// Print a cyan `info:` prefix to stdout.-pub fn info_prefix() void = trust {- terminal.print_styled("info", terminal.Color.Cyan, terminal.Color.Default, terminal.Style.Plain)- stdio.print(": ", {})-}--- a/src/src/core/primitives.sx+++ /dev/null@@ -1,30 +0,0 @@-/// 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--- a/src/src/core/reader.sx+++ /dev/null@@ -1,189 +0,0 @@-/// 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++- 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 += 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 += 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 += 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 += 7- i++- }- 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 += 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()-}--- a/src/src/crypto/blake3.sx+++ /dev/null@@ -1,374 +0,0 @@-/// 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++- }-- 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++- }-}--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++- }-}--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++- }-- @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++- }-}--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)-}--extern (C) fn veins_blake3(data: ref u8, len: usize, out: ref u8) void = "veins_blake3"-extern (C) fn veins_blake3_state_size() usize = "veins_blake3_state_size"-extern (C) fn veins_blake3_init(state: ref void) void = "veins_blake3_init"-extern (C) fn veins_blake3_update(- state: ref void,- data: ref u8,- len: usize-) void = "veins_blake3_update"-extern (C) fn veins_blake3_final(state: ref void, out: ref u8) void = "veins_blake3_final"--pub fn hasher_state_size() usize = trust {- return veins_blake3_state_size()-}--pub fn hasher_init(state: ref void) void = trust {- veins_blake3_init(state)-}--pub fn hasher_update(state: ref void, data: ref u8, len: usize) void = trust {- veins_blake3_update(state, data, len)-}--pub fn hasher_final(state: ref void, out: ref u8) void = trust {- veins_blake3_final(state, out)-}--/// Hash `len` bytes at `data` and write the 32-byte digest to `out`.-///-/// The production build links the scalar C implementation. The pure-/// implementation below is retained for format tests and fallback use.-pub fn hash(data: ref u8, len: usize, out: ref u8) void = trust {- veins_blake3(data, len, out)-}--pub fn hash_pure(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--- 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++- i++- }-- 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--- 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++- }-- @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)-}--- a/src/src/crypto/blake3/LICENSE_A2+++ /dev/null@@ -1,202 +0,0 @@-- Apache License- Version 2.0, January 2004- http://www.apache.org/licenses/-- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION-- 1. Definitions.-- "License" shall mean the terms and conditions for use, reproduction,- and distribution as defined by Sections 1 through 9 of this document.-- "Licensor" shall mean the copyright owner or entity authorized by- the copyright owner that is granting the License.-- "Legal Entity" shall mean the union of the acting entity and all- other entities that control, are controlled by, or are under common- control with that entity. For the purposes of this definition,- "control" means (i) the power, direct or indirect, to cause the- direction or management of such entity, whether by contract or- otherwise, or (ii) ownership of fifty percent (50%) or more of the- outstanding shares, or (iii) beneficial ownership of such entity.-- "You" (or "Your") shall mean an individual or Legal Entity- exercising permissions granted by this License.-- "Source" form shall mean the preferred form for making modifications,- including but not limited to software source code, documentation- source, and configuration files.-- "Object" form shall mean any form resulting from mechanical- transformation or translation of a Source form, including but- not limited to compiled object code, generated documentation,- and conversions to other media types.-- "Work" shall mean the work of authorship, whether in Source or- Object form, made available under the License, as indicated by a- copyright notice that is included in or attached to the work- (an example is provided in the Appendix below).-- "Derivative Works" shall mean any work, whether in Source or Object- form, that is based on (or derived from) the Work and for which the- editorial revisions, annotations, elaborations, or other modifications- represent, as a whole, an original work of authorship. For the purposes- of this License, Derivative Works shall not include works that remain- separable from, or merely link (or bind by name) to the interfaces of,- the Work and Derivative Works thereof.-- "Contribution" shall mean any work of authorship, including- the original version of the Work and any modifications or additions- to that Work or Derivative Works thereof, that is intentionally- submitted to Licensor for inclusion in the Work by the copyright owner- or by an individual or Legal Entity authorized to submit on behalf of- the copyright owner. For the purposes of this definition, "submitted"- means any form of electronic, verbal, or written communication sent- to the Licensor or its representatives, including but not limited to- communication on electronic mailing lists, source code control systems,- and issue tracking systems that are managed by, or on behalf of, the- Licensor for the purpose of discussing and improving the Work, but- excluding communication that is conspicuously marked or otherwise- designated in writing by the copyright owner as "Not a Contribution."-- "Contributor" shall mean Licensor and any individual or Legal Entity- on behalf of whom a Contribution has been received by Licensor and- subsequently incorporated within the Work.-- 2. Grant of Copyright License. Subject to the terms and conditions of- this License, each Contributor hereby grants to You a perpetual,- worldwide, non-exclusive, no-charge, royalty-free, irrevocable- copyright license to reproduce, prepare Derivative Works of,- publicly display, publicly perform, sublicense, and distribute the- Work and such Derivative Works in Source or Object form.-- 3. Grant of Patent License. Subject to the terms and conditions of- this License, each Contributor hereby grants to You a perpetual,- worldwide, non-exclusive, no-charge, royalty-free, irrevocable- (except as stated in this section) patent license to make, have made,- use, offer to sell, sell, import, and otherwise transfer the Work,- where such license applies only to those patent claims licensable- by such Contributor that are necessarily infringed by their- Contribution(s) alone or by combination of their Contribution(s)- with the Work to which such Contribution(s) was submitted. If You- institute patent litigation against any entity (including a- cross-claim or counterclaim in a lawsuit) alleging that the Work- or a Contribution incorporated within the Work constitutes direct- or contributory patent infringement, then any patent licenses- granted to You under this License for that Work shall terminate- as of the date such litigation is filed.-- 4. Redistribution. You may reproduce and distribute copies of the- Work or Derivative Works thereof in any medium, with or without- modifications, and in Source or Object form, provided that You- meet the following conditions:-- (a) You must give any other recipients of the Work or- Derivative Works a copy of this License; and-- (b) You must cause any modified files to carry prominent notices- stating that You changed the files; and-- (c) You must retain, in the Source form of any Derivative Works- that You distribute, all copyright, patent, trademark, and- attribution notices from the Source form of the Work,- excluding those notices that do not pertain to any part of- the Derivative Works; and-- (d) If the Work includes a "NOTICE" text file as part of its- distribution, then any Derivative Works that You distribute must- include a readable copy of the attribution notices contained- within such NOTICE file, excluding those notices that do not- pertain to any part of the Derivative Works, in at least one- of the following places: within a NOTICE text file distributed- as part of the Derivative Works; within the Source form or- documentation, if provided along with the Derivative Works; or,- within a display generated by the Derivative Works, if and- wherever such third-party notices normally appear. The contents- of the NOTICE file are for informational purposes only and- do not modify the License. You may add Your own attribution- notices within Derivative Works that You distribute, alongside- or as an addendum to the NOTICE text from the Work, provided- that such additional attribution notices cannot be construed- as modifying the License.-- You may add Your own copyright statement to Your modifications and- may provide additional or different license terms and conditions- for use, reproduction, or distribution of Your modifications, or- for any such Derivative Works as a whole, provided Your use,- reproduction, and distribution of the Work otherwise complies with- the conditions stated in this License.-- 5. Submission of Contributions. Unless You explicitly state otherwise,- any Contribution intentionally submitted for inclusion in the Work- by You to the Licensor shall be under the terms and conditions of- this License, without any additional terms or conditions.- Notwithstanding the above, nothing herein shall supersede or modify- the terms of any separate license agreement you may have executed- with Licensor regarding such Contributions.-- 6. Trademarks. This License does not grant permission to use the trade- names, trademarks, service marks, or product names of the Licensor,- except as required for reasonable and customary use in describing the- origin of the Work and reproducing the content of the NOTICE file.-- 7. Disclaimer of Warranty. Unless required by applicable law or- agreed to in writing, Licensor provides the Work (and each- Contributor provides its Contributions) on an "AS IS" BASIS,- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or- implied, including, without limitation, any warranties or conditions- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A- PARTICULAR PURPOSE. You are solely responsible for determining the- appropriateness of using or redistributing the Work and assume any- risks associated with Your exercise of permissions under this License.-- 8. Limitation of Liability. In no event and under no legal theory,- whether in tort (including negligence), contract, or otherwise,- unless required by applicable law (such as deliberate and grossly- negligent acts) or agreed to in writing, shall any Contributor be- liable to You for damages, including any direct, indirect, special,- incidental, or consequential damages of any character arising as a- result of this License or out of the use or inability to use the- Work (including but not limited to damages for loss of goodwill,- work stoppage, computer failure or malfunction, or any and all- other commercial damages or losses), even if such Contributor- has been advised of the possibility of such damages.-- 9. Accepting Warranty or Additional Liability. While redistributing- the Work or Derivative Works thereof, You may choose to offer,- and charge a fee for, acceptance of support, warranty, indemnity,- or other liability obligations and/or rights consistent with this- License. However, in accepting such obligations, You may act only- on Your own behalf and on Your sole responsibility, not on behalf- of any other Contributor, and only if You agree to indemnify,- defend, and hold each Contributor harmless for any liability- incurred by, or claims asserted against, such Contributor by reason- of your accepting any such warranty or additional liability.-- END OF TERMS AND CONDITIONS-- APPENDIX: How to apply the Apache License to your work.-- To apply the Apache License to your work, attach the following- boilerplate notice, with the fields enclosed by brackets "[]"- replaced with your own identifying information. (Don't include- the brackets!) The text should be enclosed in the appropriate- comment syntax for the file format. We also recommend that a- file or class name and description of purpose be included on the- same "printed page" as the copyright notice for easier- identification within third-party archives.-- Copyright 2019 Jack O'Connor and Samuel Neves-- Licensed under the Apache License, Version 2.0 (the "License");- you may not use this file except in compliance with the License.- You may obtain a copy of the License at-- http://www.apache.org/licenses/LICENSE-2.0-- Unless required by applicable law or agreed to in writing, software- distributed under the License is distributed on an "AS IS" BASIS,- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- See the License for the specific language governing permissions and- limitations under the License.--- a/src/src/crypto/blake3/LICENSE_A2LLVM+++ /dev/null@@ -1,219 +0,0 @@- Apache License- Version 2.0, January 2004- http://www.apache.org/licenses/-- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION-- 1. Definitions.-- "License" shall mean the terms and conditions for use, reproduction,- and distribution as defined by Sections 1 through 9 of this document.-- "Licensor" shall mean the copyright owner or entity authorized by- the copyright owner that is granting the License.-- "Legal Entity" shall mean the union of the acting entity and all- other entities that control, are controlled by, or are under common- control with that entity. For the purposes of this definition,- "control" means (i) the power, direct or indirect, to cause the- direction or management of such entity, whether by contract or- otherwise, or (ii) ownership of fifty percent (50%) or more of the- outstanding shares, or (iii) beneficial ownership of such entity.-- "You" (or "Your") shall mean an individual or Legal Entity- exercising permissions granted by this License.-- "Source" form shall mean the preferred form for making modifications,- including but not limited to software source code, documentation- source, and configuration files.-- "Object" form shall mean any form resulting from mechanical- transformation or translation of a Source form, including but- not limited to compiled object code, generated documentation,- and conversions to other media types.-- "Work" shall mean the work of authorship, whether in Source or- Object form, made available under the License, as indicated by a- copyright notice that is included in or attached to the work- (an example is provided in the Appendix below).-- "Derivative Works" shall mean any work, whether in Source or Object- form, that is based on (or derived from) the Work and for which the- editorial revisions, annotations, elaborations, or other modifications- represent, as a whole, an original work of authorship. For the purposes- of this License, Derivative Works shall not include works that remain- separable from, or merely link (or bind by name) to the interfaces of,- the Work and Derivative Works thereof.-- "Contribution" shall mean any work of authorship, including- the original version of the Work and any modifications or additions- to that Work or Derivative Works thereof, that is intentionally- submitted to Licensor for inclusion in the Work by the copyright owner- or by an individual or Legal Entity authorized to submit on behalf of- the copyright owner. For the purposes of this definition, "submitted"- means any form of electronic, verbal, or written communication sent- to the Licensor or its representatives, including but not limited to- communication on electronic mailing lists, source code control systems,- and issue tracking systems that are managed by, or on behalf of, the- Licensor for the purpose of discussing and improving the Work, but- excluding communication that is conspicuously marked or otherwise- designated in writing by the copyright owner as "Not a Contribution."-- "Contributor" shall mean Licensor and any individual or Legal Entity- on behalf of whom a Contribution has been received by Licensor and- subsequently incorporated within the Work.-- 2. Grant of Copyright License. Subject to the terms and conditions of- this License, each Contributor hereby grants to You a perpetual,- worldwide, non-exclusive, no-charge, royalty-free, irrevocable- copyright license to reproduce, prepare Derivative Works of,- publicly display, publicly perform, sublicense, and distribute the- Work and such Derivative Works in Source or Object form.-- 3. Grant of Patent License. Subject to the terms and conditions of- this License, each Contributor hereby grants to You a perpetual,- worldwide, non-exclusive, no-charge, royalty-free, irrevocable- (except as stated in this section) patent license to make, have made,- use, offer to sell, sell, import, and otherwise transfer the Work,- where such license applies only to those patent claims licensable- by such Contributor that are necessarily infringed by their- Contribution(s) alone or by combination of their Contribution(s)- with the Work to which such Contribution(s) was submitted. If You- institute patent litigation against any entity (including a- cross-claim or counterclaim in a lawsuit) alleging that the Work- or a Contribution incorporated within the Work constitutes direct- or contributory patent infringement, then any patent licenses- granted to You under this License for that Work shall terminate- as of the date such litigation is filed.-- 4. Redistribution. You may reproduce and distribute copies of the- Work or Derivative Works thereof in any medium, with or without- modifications, and in Source or Object form, provided that You- meet the following conditions:-- (a) You must give any other recipients of the Work or- Derivative Works a copy of this License; and-- (b) You must cause any modified files to carry prominent notices- stating that You changed the files; and-- (c) You must retain, in the Source form of any Derivative Works- that You distribute, all copyright, patent, trademark, and- attribution notices from the Source form of the Work,- excluding those notices that do not pertain to any part of- the Derivative Works; and-- (d) If the Work includes a "NOTICE" text file as part of its- distribution, then any Derivative Works that You distribute must- include a readable copy of the attribution notices contained- within such NOTICE file, excluding those notices that do not- pertain to any part of the Derivative Works, in at least one- of the following places: within a NOTICE text file distributed- as part of the Derivative Works; within the Source form or- documentation, if provided along with the Derivative Works; or,- within a display generated by the Derivative Works, if and- wherever such third-party notices normally appear. The contents- of the NOTICE file are for informational purposes only and- do not modify the License. You may add Your own attribution- notices within Derivative Works that You distribute, alongside- or as an addendum to the NOTICE text from the Work, provided- that such additional attribution notices cannot be construed- as modifying the License.-- You may add Your own copyright statement to Your modifications and- may provide additional or different license terms and conditions- for use, reproduction, or distribution of Your modifications, or- for any such Derivative Works as a whole, provided Your use,- reproduction, and distribution of the Work otherwise complies with- the conditions stated in this License.-- 5. Submission of Contributions. Unless You explicitly state otherwise,- any Contribution intentionally submitted for inclusion in the Work- by You to the Licensor shall be under the terms and conditions of- this License, without any additional terms or conditions.- Notwithstanding the above, nothing herein shall supersede or modify- the terms of any separate license agreement you may have executed- with Licensor regarding such Contributions.-- 6. Trademarks. This License does not grant permission to use the trade- names, trademarks, service marks, or product names of the Licensor,- except as required for reasonable and customary use in describing the- origin of the Work and reproducing the content of the NOTICE file.-- 7. Disclaimer of Warranty. Unless required by applicable law or- agreed to in writing, Licensor provides the Work (and each- Contributor provides its Contributions) on an "AS IS" BASIS,- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or- implied, including, without limitation, any warranties or conditions- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A- PARTICULAR PURPOSE. You are solely responsible for determining the- appropriateness of using or redistributing the Work and assume any- risks associated with Your exercise of permissions under this License.-- 8. Limitation of Liability. In no event and under no legal theory,- whether in tort (including negligence), contract, or otherwise,- unless required by applicable law (such as deliberate and grossly- negligent acts) or agreed to in writing, shall any Contributor be- liable to You for damages, including any direct, indirect, special,- incidental, or consequential damages of any character arising as a- result of this License or out of the use or inability to use the- Work (including but not limited to damages for loss of goodwill,- work stoppage, computer failure or malfunction, or any and all- other commercial damages or losses), even if such Contributor- has been advised of the possibility of such damages.-- 9. Accepting Warranty or Additional Liability. While redistributing- the Work or Derivative Works thereof, You may choose to offer,- and charge a fee for, acceptance of support, warranty, indemnity,- or other liability obligations and/or rights consistent with this- License. However, in accepting such obligations, You may act only- on Your own behalf and on Your sole responsibility, not on behalf- of any other Contributor, and only if You agree to indemnify,- defend, and hold each Contributor harmless for any liability- incurred by, or claims asserted against, such Contributor by reason- of your accepting any such warranty or additional liability.-- END OF TERMS AND CONDITIONS-- APPENDIX: How to apply the Apache License to your work.-- To apply the Apache License to your work, attach the following- boilerplate notice, with the fields enclosed by brackets "[]"- replaced with your own identifying information. (Don't include- the brackets!) The text should be enclosed in the appropriate- comment syntax for the file format. We also recommend that a- file or class name and description of purpose be included on the- same "printed page" as the copyright notice for easier- identification within third-party archives.-- Copyright 2019 Jack O'Connor and Samuel Neves-- Licensed under the Apache License, Version 2.0 (the "License");- you may not use this file except in compliance with the License.- You may obtain a copy of the License at-- http://www.apache.org/licenses/LICENSE-2.0-- Unless required by applicable law or agreed to in writing, software- distributed under the License is distributed on an "AS IS" BASIS,- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- See the License for the specific language governing permissions and- limitations under the License.------- LLVM Exceptions to the Apache 2.0 License ------As an exception, if, as a result of your compiling your source code, portions-of this Software are embedded into an Object form of such source code, you-may redistribute such embedded portions in such Object form without complying-with the conditions of Sections 4(a), 4(b) and 4(d) of the License.--In addition, if you combine or link compiled forms of this Software with-software that is licensed under the GPLv2 ("Combined Software") and if a-court of competent jurisdiction determines that the patent provision (Section-3), the indemnity provision (Section 9) or other Section of the License-conflicts with the conditions of the GPLv2, you may retroactively and-prospectively choose to deem waived or otherwise exclude such Section(s) of-the License, but only in their entirety and only with respect to the Combined-Software.---- a/src/src/crypto/blake3/LICENSE_CC0+++ /dev/null@@ -1,121 +0,0 @@-Creative Commons Legal Code--CC0 1.0 Universal-- CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE- LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN- ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS- INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES- REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS- PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM- THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED- HEREUNDER.--Statement of Purpose--The laws of most jurisdictions throughout the world automatically confer-exclusive Copyright and Related Rights (defined below) upon the creator-and subsequent owner(s) (each and all, an "owner") of an original work of-authorship and/or a database (each, a "Work").--Certain owners wish to permanently relinquish those rights to a Work for-the purpose of contributing to a commons of creative, cultural and-scientific works ("Commons") that the public can reliably and without fear-of later claims of infringement build upon, modify, incorporate in other-works, reuse and redistribute as freely as possible in any form whatsoever-and for any purposes, including without limitation commercial purposes.-These owners may contribute to the Commons to promote the ideal of a free-culture and the further production of creative, cultural and scientific-works, or to gain reputation or greater distribution for their Work in-part through the use and efforts of others.--For these and/or other purposes and motivations, and without any-expectation of additional consideration or compensation, the person-associating CC0 with a Work (the "Affirmer"), to the extent that he or she-is an owner of Copyright and Related Rights in the Work, voluntarily-elects to apply CC0 to the Work and publicly distribute the Work under its-terms, with knowledge of his or her Copyright and Related Rights in the-Work and the meaning and intended legal effect of CC0 on those rights.--1. Copyright and Related Rights. A Work made available under CC0 may be-protected by copyright and related or neighboring rights ("Copyright and-Related Rights"). Copyright and Related Rights include, but are not-limited to, the following:-- i. the right to reproduce, adapt, distribute, perform, display,- communicate, and translate a Work;- ii. moral rights retained by the original author(s) and/or performer(s);-iii. publicity and privacy rights pertaining to a person's image or- likeness depicted in a Work;- iv. rights protecting against unfair competition in regards to a Work,- subject to the limitations in paragraph 4(a), below;- v. rights protecting the extraction, dissemination, use and reuse of data- in a Work;- vi. database rights (such as those arising under Directive 96/9/EC of the- European Parliament and of the Council of 11 March 1996 on the legal- protection of databases, and under any national implementation- thereof, including any amended or successor version of such- directive); and-vii. other similar, equivalent or corresponding rights throughout the- world based on applicable law or treaty, and any national- implementations thereof.--2. Waiver. To the greatest extent permitted by, but not in contravention-of, applicable law, Affirmer hereby overtly, fully, permanently,-irrevocably and unconditionally waives, abandons, and surrenders all of-Affirmer's Copyright and Related Rights and associated claims and causes-of action, whether now known or unknown (including existing as well as-future claims and causes of action), in the Work (i) in all territories-worldwide, (ii) for the maximum duration provided by applicable law or-treaty (including future time extensions), (iii) in any current or future-medium and for any number of copies, and (iv) for any purpose whatsoever,-including without limitation commercial, advertising or promotional-purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each-member of the public at large and to the detriment of Affirmer's heirs and-successors, fully intending that such Waiver shall not be subject to-revocation, rescission, cancellation, termination, or any other legal or-equitable action to disrupt the quiet enjoyment of the Work by the public-as contemplated by Affirmer's express Statement of Purpose.--3. Public License Fallback. Should any part of the Waiver for any reason-be judged legally invalid or ineffective under applicable law, then the-Waiver shall be preserved to the maximum extent permitted taking into-account Affirmer's express Statement of Purpose. In addition, to the-extent the Waiver is so judged Affirmer hereby grants to each affected-person a royalty-free, non transferable, non sublicensable, non exclusive,-irrevocable and unconditional license to exercise Affirmer's Copyright and-Related Rights in the Work (i) in all territories worldwide, (ii) for the-maximum duration provided by applicable law or treaty (including future-time extensions), (iii) in any current or future medium and for any number-of copies, and (iv) for any purpose whatsoever, including without-limitation commercial, advertising or promotional purposes (the-"License"). The License shall be deemed effective as of the date CC0 was-applied by Affirmer to the Work. Should any part of the License for any-reason be judged legally invalid or ineffective under applicable law, such-partial invalidity or ineffectiveness shall not invalidate the remainder-of the License, and in such case Affirmer hereby affirms that he or she-will not (i) exercise any of his or her remaining Copyright and Related-Rights in the Work or (ii) assert any associated claims and causes of-action with respect to the Work, in either case contrary to Affirmer's-express Statement of Purpose.--4. Limitations and Disclaimers.-- a. No trademark or patent rights held by Affirmer are waived, abandoned,- surrendered, licensed or otherwise affected by this document.- b. Affirmer offers the Work as-is and makes no representations or- warranties of any kind concerning the Work, express, implied,- statutory or otherwise, including without limitation warranties of- title, merchantability, fitness for a particular purpose, non- infringement, or the absence of latent or other defects, accuracy, or- the present or absence of errors, whether or not discoverable, all to- the greatest extent permissible under applicable law.- c. Affirmer disclaims responsibility for clearing rights of other persons- that may apply to the Work or any use thereof, including without- limitation any person's Copyright and Related Rights in the Work.- Further, Affirmer disclaims responsibility for obtaining any necessary- consents, permissions or other rights required for any use of the- Work.- d. Affirmer understands and acknowledges that Creative Commons is not a- party to this document and has no duty or obligation with respect to- this CC0 or use of the Work.--- a/src/src/crypto/blake3/blake3.c+++ /dev/null@@ -1,651 +0,0 @@-#include <assert.h>-#include <stdbool.h>-#include <string.h>-#include <stdint.h>--#include "blake3.h"-#include "blake3_impl.h"--const char *blake3_version(void) { return BLAKE3_VERSION_STRING; }--INLINE void chunk_state_init(blake3_chunk_state *self, const uint32_t key[8],- uint8_t flags) {- memcpy(self->cv, key, BLAKE3_KEY_LEN);- self->chunk_counter = 0;- memset(self->buf, 0, BLAKE3_BLOCK_LEN);- self->buf_len = 0;- self->blocks_compressed = 0;- self->flags = flags;-}--INLINE void chunk_state_reset(blake3_chunk_state *self, const uint32_t key[8],- uint64_t chunk_counter) {- memcpy(self->cv, key, BLAKE3_KEY_LEN);- self->chunk_counter = chunk_counter;- self->blocks_compressed = 0;- memset(self->buf, 0, BLAKE3_BLOCK_LEN);- self->buf_len = 0;-}--INLINE size_t chunk_state_len(const blake3_chunk_state *self) {- return (BLAKE3_BLOCK_LEN * (size_t)self->blocks_compressed) +- ((size_t)self->buf_len);-}--INLINE size_t chunk_state_fill_buf(blake3_chunk_state *self,- const uint8_t *input, size_t input_len) {- size_t take = BLAKE3_BLOCK_LEN - ((size_t)self->buf_len);- if (take > input_len) {- take = input_len;- }- uint8_t *dest = self->buf + ((size_t)self->buf_len);- memcpy(dest, input, take);- self->buf_len += (uint8_t)take;- return take;-}--INLINE uint8_t chunk_state_maybe_start_flag(const blake3_chunk_state *self) {- if (self->blocks_compressed == 0) {- return CHUNK_START;- } else {- return 0;- }-}--typedef struct {- uint32_t input_cv[8];- uint64_t counter;- uint8_t block[BLAKE3_BLOCK_LEN];- uint8_t block_len;- uint8_t flags;-} output_t;--INLINE output_t make_output(const uint32_t input_cv[8],- const uint8_t block[BLAKE3_BLOCK_LEN],- uint8_t block_len, uint64_t counter,- uint8_t flags) {- output_t ret;- memcpy(ret.input_cv, input_cv, 32);- memcpy(ret.block, block, BLAKE3_BLOCK_LEN);- ret.block_len = block_len;- ret.counter = counter;- ret.flags = flags;- return ret;-}--// Chaining values within a given chunk (specifically the compress_in_place-// interface) are represented as words. This avoids unnecessary bytes<->words-// conversion overhead in the portable implementation. However, the hash_many-// interface handles both user input and parent node blocks, so it accepts-// bytes. For that reason, chaining values in the CV stack are represented as-// bytes.-INLINE void output_chaining_value(const output_t *self, uint8_t cv[32]) {- uint32_t cv_words[8];- memcpy(cv_words, self->input_cv, 32);- blake3_compress_in_place(cv_words, self->block, self->block_len,- self->counter, self->flags);- store_cv_words(cv, cv_words);-}--INLINE void output_root_bytes(const output_t *self, uint64_t seek, uint8_t *out,- size_t out_len) {- if (out_len == 0) {- return;- }- uint64_t output_block_counter = seek / 64;- size_t offset_within_block = seek % 64;- uint8_t wide_buf[64];- if(offset_within_block) {- blake3_compress_xof(self->input_cv, self->block, self->block_len, output_block_counter, self->flags | ROOT, wide_buf);- const size_t available_bytes = 64 - offset_within_block;- const size_t bytes = out_len > available_bytes ? available_bytes : out_len;- memcpy(out, wide_buf + offset_within_block, bytes);- out += bytes;- out_len -= bytes;- output_block_counter += 1;- }- if(out_len / 64) {- blake3_xof_many(self->input_cv, self->block, self->block_len, output_block_counter, self->flags | ROOT, out, out_len / 64);- }- output_block_counter += out_len / 64;- out += out_len & -64;- out_len -= out_len & -64;- if(out_len) {- blake3_compress_xof(self->input_cv, self->block, self->block_len, output_block_counter, self->flags | ROOT, wide_buf);- memcpy(out, wide_buf, out_len);- }-}--INLINE void chunk_state_update(blake3_chunk_state *self, const uint8_t *input,- size_t input_len) {- if (self->buf_len > 0) {- size_t take = chunk_state_fill_buf(self, input, input_len);- input += take;- input_len -= take;- if (input_len > 0) {- blake3_compress_in_place(- self->cv, self->buf, BLAKE3_BLOCK_LEN, self->chunk_counter,- self->flags | chunk_state_maybe_start_flag(self));- self->blocks_compressed += 1;- self->buf_len = 0;- memset(self->buf, 0, BLAKE3_BLOCK_LEN);- }- }-- while (input_len > BLAKE3_BLOCK_LEN) {- blake3_compress_in_place(self->cv, input, BLAKE3_BLOCK_LEN,- self->chunk_counter,- self->flags | chunk_state_maybe_start_flag(self));- self->blocks_compressed += 1;- input += BLAKE3_BLOCK_LEN;- input_len -= BLAKE3_BLOCK_LEN;- }-- chunk_state_fill_buf(self, input, input_len);-}--INLINE output_t chunk_state_output(const blake3_chunk_state *self) {- uint8_t block_flags =- self->flags | chunk_state_maybe_start_flag(self) | CHUNK_END;- return make_output(self->cv, self->buf, self->buf_len, self->chunk_counter,- block_flags);-}--INLINE output_t parent_output(const uint8_t block[BLAKE3_BLOCK_LEN],- const uint32_t key[8], uint8_t flags) {- return make_output(key, block, BLAKE3_BLOCK_LEN, 0, flags | PARENT);-}--// Given some input larger than one chunk, return the number of bytes that-// should go in the left subtree. This is the largest power-of-2 number of-// chunks that leaves at least 1 byte for the right subtree.-INLINE size_t left_subtree_len(size_t input_len) {- // Subtract 1 to reserve at least one byte for the right side. input_len- // should always be greater than BLAKE3_CHUNK_LEN.- size_t full_chunks = (input_len - 1) / BLAKE3_CHUNK_LEN;- return round_down_to_power_of_2(full_chunks) * BLAKE3_CHUNK_LEN;-}--// Use SIMD parallelism to hash up to MAX_SIMD_DEGREE chunks at the same time-// on a single thread. Write out the chunk chaining values and return the-// number of chunks hashed. These chunks are never the root and never empty;-// those cases use a different codepath.-INLINE size_t compress_chunks_parallel(const uint8_t *input, size_t input_len,- const uint32_t key[8],- uint64_t chunk_counter, uint8_t flags,- uint8_t *out) {-#if defined(BLAKE3_TESTING)- assert(0 < input_len);- assert(input_len <= MAX_SIMD_DEGREE * BLAKE3_CHUNK_LEN);-#endif-- const uint8_t *chunks_array[MAX_SIMD_DEGREE];- size_t input_position = 0;- size_t chunks_array_len = 0;- while (input_len - input_position >= BLAKE3_CHUNK_LEN) {- chunks_array[chunks_array_len] = &input[input_position];- input_position += BLAKE3_CHUNK_LEN;- chunks_array_len += 1;- }-- blake3_hash_many(chunks_array, chunks_array_len,- BLAKE3_CHUNK_LEN / BLAKE3_BLOCK_LEN, key, chunk_counter,- true, flags, CHUNK_START, CHUNK_END, out);-- // Hash the remaining partial chunk, if there is one. Note that the empty- // chunk (meaning the empty message) is a different codepath.- if (input_len > input_position) {- uint64_t counter = chunk_counter + (uint64_t)chunks_array_len;- blake3_chunk_state chunk_state;- chunk_state_init(&chunk_state, key, flags);- chunk_state.chunk_counter = counter;- chunk_state_update(&chunk_state, &input[input_position],- input_len - input_position);- output_t output = chunk_state_output(&chunk_state);- output_chaining_value(&output, &out[chunks_array_len * BLAKE3_OUT_LEN]);- return chunks_array_len + 1;- } else {- return chunks_array_len;- }-}--// Use SIMD parallelism to hash up to MAX_SIMD_DEGREE parents at the same time-// on a single thread. Write out the parent chaining values and return the-// number of parents hashed. (If there's an odd input chaining value left over,-// return it as an additional output.) These parents are never the root and-// never empty; those cases use a different codepath.-INLINE size_t compress_parents_parallel(const uint8_t *child_chaining_values,- size_t num_chaining_values,- const uint32_t key[8], uint8_t flags,- uint8_t *out) {-#if defined(BLAKE3_TESTING)- assert(2 <= num_chaining_values);- assert(num_chaining_values <= 2 * MAX_SIMD_DEGREE_OR_2);-#endif-- const uint8_t *parents_array[MAX_SIMD_DEGREE_OR_2];- size_t parents_array_len = 0;- while (num_chaining_values - (2 * parents_array_len) >= 2) {- parents_array[parents_array_len] =- &child_chaining_values[2 * parents_array_len * BLAKE3_OUT_LEN];- parents_array_len += 1;- }-- blake3_hash_many(parents_array, parents_array_len, 1, key,- 0, // Parents always use counter 0.- false, flags | PARENT,- 0, // Parents have no start flags.- 0, // Parents have no end flags.- out);-- // If there's an odd child left over, it becomes an output.- if (num_chaining_values > 2 * parents_array_len) {- memcpy(&out[parents_array_len * BLAKE3_OUT_LEN],- &child_chaining_values[2 * parents_array_len * BLAKE3_OUT_LEN],- BLAKE3_OUT_LEN);- return parents_array_len + 1;- } else {- return parents_array_len;- }-}--// The wide helper function returns (writes out) an array of chaining values-// and returns the length of that array. The number of chaining values returned-// is the dynamically detected SIMD degree, at most MAX_SIMD_DEGREE. Or fewer,-// if the input is shorter than that many chunks. The reason for maintaining a-// wide array of chaining values going back up the tree, is to allow the-// implementation to hash as many parents in parallel as possible.-//-// As a special case when the SIMD degree is 1, this function will still return-// at least 2 outputs. This guarantees that this function doesn't perform the-// root compression. (If it did, it would use the wrong flags, and also we-// wouldn't be able to implement extendable output.) Note that this function is-// not used when the whole input is only 1 chunk long; that's a different-// codepath.-//-// Why not just have the caller split the input on the first update(), instead-// of implementing this special rule? Because we don't want to limit SIMD or-// multi-threading parallelism for that update().-size_t blake3_compress_subtree_wide(const uint8_t *input, size_t input_len,- const uint32_t key[8],- uint64_t chunk_counter, uint8_t flags,- uint8_t *out, bool use_tbb) {- // Note that the single chunk case does *not* bump the SIMD degree up to 2- // when it is 1. If this implementation adds multi-threading in the future,- // this gives us the option of multi-threading even the 2-chunk case, which- // can help performance on smaller platforms.- if (input_len <= blake3_simd_degree() * BLAKE3_CHUNK_LEN) {- return compress_chunks_parallel(input, input_len, key, chunk_counter, flags,- out);- }-- // With more than simd_degree chunks, we need to recurse. Start by dividing- // the input into left and right subtrees. (Note that this is only optimal- // as long as the SIMD degree is a power of 2. If we ever get a SIMD degree- // of 3 or something, we'll need a more complicated strategy.)- size_t left_input_len = left_subtree_len(input_len);- size_t right_input_len = input_len - left_input_len;- const uint8_t *right_input = &input[left_input_len];- uint64_t right_chunk_counter =- chunk_counter + (uint64_t)(left_input_len / BLAKE3_CHUNK_LEN);-- // Make space for the child outputs. Here we use MAX_SIMD_DEGREE_OR_2 to- // account for the special case of returning 2 outputs when the SIMD degree- // is 1.- uint8_t cv_array[2 * MAX_SIMD_DEGREE_OR_2 * BLAKE3_OUT_LEN];- size_t degree = blake3_simd_degree();- if (left_input_len > BLAKE3_CHUNK_LEN && degree == 1) {- // The special case: We always use a degree of at least two, to make- // sure there are two outputs. Except, as noted above, at the chunk- // level, where we allow degree=1. (Note that the 1-chunk-input case is- // a different codepath.)- degree = 2;- }- uint8_t *right_cvs = &cv_array[degree * BLAKE3_OUT_LEN];-- // Recurse!- size_t left_n = SIZE_MAX;- size_t right_n = SIZE_MAX;--#if defined(BLAKE3_USE_TBB)- blake3_compress_subtree_wide_join_tbb(- key, flags, use_tbb,- // left-hand side- input, left_input_len, chunk_counter, cv_array, &left_n,- // right-hand side- right_input, right_input_len, right_chunk_counter, right_cvs, &right_n);-#else- left_n = blake3_compress_subtree_wide(- input, left_input_len, key, chunk_counter, flags, cv_array, use_tbb);- right_n = blake3_compress_subtree_wide(right_input, right_input_len, key,- right_chunk_counter, flags, right_cvs,- use_tbb);-#endif // BLAKE3_USE_TBB-- // The special case again. If simd_degree=1, then we'll have left_n=1 and- // right_n=1. Rather than compressing them into a single output, return- // them directly, to make sure we always have at least two outputs.- if (left_n == 1) {- memcpy(out, cv_array, 2 * BLAKE3_OUT_LEN);- return 2;- }-- // Otherwise, do one layer of parent node compression.- size_t num_chaining_values = left_n + right_n;- return compress_parents_parallel(cv_array, num_chaining_values, key, flags,- out);-}--// Hash a subtree with compress_subtree_wide(), and then condense the resulting-// list of chaining values down to a single parent node. Don't compress that-// last parent node, however. Instead, return its message bytes (the-// concatenated chaining values of its children). This is necessary when the-// first call to update() supplies a complete subtree, because the topmost-// parent node of that subtree could end up being the root. It's also necessary-// for extended output in the general case.-//-// As with compress_subtree_wide(), this function is not used on inputs of 1-// chunk or less. That's a different codepath.-INLINE void-compress_subtree_to_parent_node(const uint8_t *input, size_t input_len,- const uint32_t key[8], uint64_t chunk_counter,- uint8_t flags, uint8_t out[2 * BLAKE3_OUT_LEN],- bool use_tbb) {-#if defined(BLAKE3_TESTING)- assert(input_len > BLAKE3_CHUNK_LEN);-#endif-- uint8_t cv_array[MAX_SIMD_DEGREE_OR_2 * BLAKE3_OUT_LEN];- size_t num_cvs = blake3_compress_subtree_wide(input, input_len, key,- chunk_counter, flags, cv_array, use_tbb);- assert(num_cvs <= MAX_SIMD_DEGREE_OR_2);- // The following loop never executes when MAX_SIMD_DEGREE_OR_2 is 2, because- // as we just asserted, num_cvs will always be <=2 in that case. But GCC- // (particularly GCC 8.5) can't tell that it never executes, and if NDEBUG is- // set then it emits incorrect warnings here. We tried a few different- // hacks to silence these, but in the end our hacks just produced different- // warnings (see https://github.com/BLAKE3-team/BLAKE3/pull/380). Out of- // desperation, we ifdef out this entire loop when we know it's not needed.-#if MAX_SIMD_DEGREE_OR_2 > 2- // If MAX_SIMD_DEGREE_OR_2 is greater than 2 and there's enough input,- // compress_subtree_wide() returns more than 2 chaining values. Condense- // them into 2 by forming parent nodes repeatedly.- uint8_t out_array[MAX_SIMD_DEGREE_OR_2 * BLAKE3_OUT_LEN / 2];- while (num_cvs > 2) {- num_cvs =- compress_parents_parallel(cv_array, num_cvs, key, flags, out_array);- memcpy(cv_array, out_array, num_cvs * BLAKE3_OUT_LEN);- }-#endif- memcpy(out, cv_array, 2 * BLAKE3_OUT_LEN);-}--INLINE void hasher_init_base(blake3_hasher *self, const uint32_t key[8],- uint8_t flags) {- memcpy(self->key, key, BLAKE3_KEY_LEN);- chunk_state_init(&self->chunk, key, flags);- self->cv_stack_len = 0;-}--void blake3_hasher_init(blake3_hasher *self) { hasher_init_base(self, IV, 0); }--void blake3_hasher_init_keyed(blake3_hasher *self,- const uint8_t key[BLAKE3_KEY_LEN]) {- uint32_t key_words[8];- load_key_words(key, key_words);- hasher_init_base(self, key_words, KEYED_HASH);-}--void blake3_hasher_init_derive_key_raw(blake3_hasher *self, const void *context,- size_t context_len) {- blake3_hasher context_hasher;- hasher_init_base(&context_hasher, IV, DERIVE_KEY_CONTEXT);- blake3_hasher_update(&context_hasher, context, context_len);- uint8_t context_key[BLAKE3_KEY_LEN];- blake3_hasher_finalize(&context_hasher, context_key, BLAKE3_KEY_LEN);- uint32_t context_key_words[8];- load_key_words(context_key, context_key_words);- hasher_init_base(self, context_key_words, DERIVE_KEY_MATERIAL);-}--void blake3_hasher_init_derive_key(blake3_hasher *self, const char *context) {- blake3_hasher_init_derive_key_raw(self, context, strlen(context));-}--// As described in hasher_push_cv() below, we do "lazy merging", delaying-// merges until right before the next CV is about to be added. This is-// different from the reference implementation. Another difference is that we-// aren't always merging 1 chunk at a time. Instead, each CV might represent-// any power-of-two number of chunks, as long as the smaller-above-larger stack-// order is maintained. Instead of the "count the trailing 0-bits" algorithm-// described in the spec, we use a "count the total number of 1-bits" variant-// that doesn't require us to retain the subtree size of the CV on top of the-// stack. The principle is the same: each CV that should remain in the stack is-// represented by a 1-bit in the total number of chunks (or bytes) so far.-INLINE void hasher_merge_cv_stack(blake3_hasher *self, uint64_t total_len) {- size_t post_merge_stack_len = (size_t)popcnt(total_len);- while (self->cv_stack_len > post_merge_stack_len) {- uint8_t *parent_node =- &self->cv_stack[(self->cv_stack_len - 2) * BLAKE3_OUT_LEN];- output_t output = parent_output(parent_node, self->key, self->chunk.flags);- output_chaining_value(&output, parent_node);- self->cv_stack_len -= 1;- }-}--// In reference_impl.rs, we merge the new CV with existing CVs from the stack-// before pushing it. We can do that because we know more input is coming, so-// we know none of the merges are root.-//-// This setting is different. We want to feed as much input as possible to-// compress_subtree_wide(), without setting aside anything for the chunk_state.-// If the user gives us 64 KiB, we want to parallelize over all 64 KiB at once-// as a single subtree, if at all possible.-//-// This leads to two problems:-// 1) This 64 KiB input might be the only call that ever gets made to update.-// In this case, the root node of the 64 KiB subtree would be the root node-// of the whole tree, and it would need to be ROOT finalized. We can't-// compress it until we know.-// 2) This 64 KiB input might complete a larger tree, whose root node is-// similarly going to be the root of the whole tree. For example, maybe-// we have 196 KiB (that is, 128 + 64) hashed so far. We can't compress the-// node at the root of the 256 KiB subtree until we know how to finalize it.-//-// The second problem is solved with "lazy merging". That is, when we're about-// to add a CV to the stack, we don't merge it with anything first, as the-// reference impl does. Instead we do merges using the *previous* CV that was-// added, which is sitting on top of the stack, and we put the new CV-// (unmerged) on top of the stack afterwards. This guarantees that we never-// merge the root node until finalize().-//-// Solving the first problem requires an additional tool,-// compress_subtree_to_parent_node(). That function always returns the top-// *two* chaining values of the subtree it's compressing. We then do lazy-// merging with each of them separately, so that the second CV will always-// remain unmerged. (That also helps us support extendable output when we're-// hashing an input all-at-once.)-INLINE void hasher_push_cv(blake3_hasher *self, uint8_t new_cv[BLAKE3_OUT_LEN],- uint64_t chunk_counter) {- hasher_merge_cv_stack(self, chunk_counter);- memcpy(&self->cv_stack[self->cv_stack_len * BLAKE3_OUT_LEN], new_cv,- BLAKE3_OUT_LEN);- self->cv_stack_len += 1;-}--INLINE void blake3_hasher_update_base(blake3_hasher *self, const void *input,- size_t input_len, bool use_tbb) {- // Explicitly checking for zero avoids causing UB by passing a null pointer- // to memcpy. This comes up in practice with things like:- // std::vector<uint8_t> v;- // blake3_hasher_update(&hasher, v.data(), v.size());- if (input_len == 0) {- return;- }-- const uint8_t *input_bytes = (const uint8_t *)input;-- // If we have some partial chunk bytes in the internal chunk_state, we need- // to finish that chunk first.- if (chunk_state_len(&self->chunk) > 0) {- size_t take = BLAKE3_CHUNK_LEN - chunk_state_len(&self->chunk);- if (take > input_len) {- take = input_len;- }- chunk_state_update(&self->chunk, input_bytes, take);- input_bytes += take;- input_len -= take;- // If we've filled the current chunk and there's more coming, finalize this- // chunk and proceed. In this case we know it's not the root.- if (input_len > 0) {- output_t output = chunk_state_output(&self->chunk);- uint8_t chunk_cv[32];- output_chaining_value(&output, chunk_cv);- hasher_push_cv(self, chunk_cv, self->chunk.chunk_counter);- chunk_state_reset(&self->chunk, self->key, self->chunk.chunk_counter + 1);- } else {- return;- }- }-- // Now the chunk_state is clear, and we have more input. If there's more than- // a single chunk (so, definitely not the root chunk), hash the largest whole- // subtree we can, with the full benefits of SIMD (and maybe in the future,- // multi-threading) parallelism. Two restrictions:- // - The subtree has to be a power-of-2 number of chunks. Only subtrees along- // the right edge can be incomplete, and we don't know where the right edge- // is going to be until we get to finalize().- // - The subtree must evenly divide the total number of chunks up until this- // point (if total is not 0). If the current incomplete subtree is only- // waiting for 1 more chunk, we can't hash a subtree of 4 chunks. We have- // to complete the current subtree first.- // Because we might need to break up the input to form powers of 2, or to- // evenly divide what we already have, this part runs in a loop.- while (input_len > BLAKE3_CHUNK_LEN) {- size_t subtree_len = round_down_to_power_of_2(input_len);- uint64_t count_so_far = self->chunk.chunk_counter * BLAKE3_CHUNK_LEN;- // Shrink the subtree_len until it evenly divides the count so far. We know- // that subtree_len itself is a power of 2, so we can use a bitmasking- // trick instead of an actual remainder operation. (Note that if the caller- // consistently passes power-of-2 inputs of the same size, as is hopefully- // typical, this loop condition will always fail, and subtree_len will- // always be the full length of the input.)- //- // An aside: We don't have to shrink subtree_len quite this much. For- // example, if count_so_far is 1, we could pass 2 chunks to- // compress_subtree_to_parent_node. Since we'll get 2 CVs back, we'll still- // get the right answer in the end, and we might get to use 2-way SIMD- // parallelism. The problem with this optimization, is that it gets us- // stuck always hashing 2 chunks. The total number of chunks will remain- // odd, and we'll never graduate to higher degrees of parallelism. See- // https://github.com/BLAKE3-team/BLAKE3/issues/69.- while ((((uint64_t)(subtree_len - 1)) & count_so_far) != 0) {- subtree_len /= 2;- }- // The shrunken subtree_len might now be 1 chunk long. If so, hash that one- // chunk by itself. Otherwise, compress the subtree into a pair of CVs.- uint64_t subtree_chunks = subtree_len / BLAKE3_CHUNK_LEN;- if (subtree_len <= BLAKE3_CHUNK_LEN) {- blake3_chunk_state chunk_state;- chunk_state_init(&chunk_state, self->key, self->chunk.flags);- chunk_state.chunk_counter = self->chunk.chunk_counter;- chunk_state_update(&chunk_state, input_bytes, subtree_len);- output_t output = chunk_state_output(&chunk_state);- uint8_t cv[BLAKE3_OUT_LEN];- output_chaining_value(&output, cv);- hasher_push_cv(self, cv, chunk_state.chunk_counter);- } else {- // This is the high-performance happy path, though getting here depends- // on the caller giving us a long enough input.- uint8_t cv_pair[2 * BLAKE3_OUT_LEN];- compress_subtree_to_parent_node(input_bytes, subtree_len, self->key,- self->chunk.chunk_counter,- self->chunk.flags, cv_pair, use_tbb);- hasher_push_cv(self, cv_pair, self->chunk.chunk_counter);- hasher_push_cv(self, &cv_pair[BLAKE3_OUT_LEN],- self->chunk.chunk_counter + (subtree_chunks / 2));- }- self->chunk.chunk_counter += subtree_chunks;- input_bytes += subtree_len;- input_len -= subtree_len;- }-- // If there's any remaining input less than a full chunk, add it to the chunk- // state. In that case, also do a final merge loop to make sure the subtree- // stack doesn't contain any unmerged pairs. The remaining input means we- // know these merges are non-root. This merge loop isn't strictly necessary- // here, because hasher_push_chunk_cv already does its own merge loop, but it- // simplifies blake3_hasher_finalize below.- if (input_len > 0) {- chunk_state_update(&self->chunk, input_bytes, input_len);- hasher_merge_cv_stack(self, self->chunk.chunk_counter);- }-}--void blake3_hasher_update(blake3_hasher *self, const void *input,- size_t input_len) {- bool use_tbb = false;- blake3_hasher_update_base(self, input, input_len, use_tbb);-}--#if defined(BLAKE3_USE_TBB)-void blake3_hasher_update_tbb(blake3_hasher *self, const void *input,- size_t input_len) {- bool use_tbb = true;- blake3_hasher_update_base(self, input, input_len, use_tbb);-}-#endif // BLAKE3_USE_TBB--void blake3_hasher_finalize(const blake3_hasher *self, uint8_t *out,- size_t out_len) {- blake3_hasher_finalize_seek(self, 0, out, out_len);-}--void blake3_hasher_finalize_seek(const blake3_hasher *self, uint64_t seek,- uint8_t *out, size_t out_len) {- // Explicitly checking for zero avoids causing UB by passing a null pointer- // to memcpy. This comes up in practice with things like:- // std::vector<uint8_t> v;- // blake3_hasher_finalize(&hasher, v.data(), v.size());- if (out_len == 0) {- return;- }-- // If the subtree stack is empty, then the current chunk is the root.- if (self->cv_stack_len == 0) {- output_t output = chunk_state_output(&self->chunk);- output_root_bytes(&output, seek, out, out_len);- return;- }- // If there are any bytes in the chunk state, finalize that chunk and do a- // roll-up merge between that chunk hash and every subtree in the stack. In- // this case, the extra merge loop at the end of blake3_hasher_update- // guarantees that none of the subtrees in the stack need to be merged with- // each other first. Otherwise, if there are no bytes in the chunk state,- // then the top of the stack is a chunk hash, and we start the merge from- // that.- output_t output;- size_t cvs_remaining;- if (chunk_state_len(&self->chunk) > 0) {- cvs_remaining = self->cv_stack_len;- output = chunk_state_output(&self->chunk);- } else {- // There are always at least 2 CVs in the stack in this case.- cvs_remaining = self->cv_stack_len - 2;- output = parent_output(&self->cv_stack[cvs_remaining * 32], self->key,- self->chunk.flags);- }- while (cvs_remaining > 0) {- cvs_remaining -= 1;- uint8_t parent_block[BLAKE3_BLOCK_LEN];- memcpy(parent_block, &self->cv_stack[cvs_remaining * 32], 32);- output_chaining_value(&output, &parent_block[32]);- output = parent_output(parent_block, self->key, self->chunk.flags);- }- output_root_bytes(&output, seek, out, out_len);-}--void blake3_hasher_reset(blake3_hasher *self) {- chunk_state_reset(&self->chunk, self->key, 0);- self->cv_stack_len = 0;-}--- a/src/src/crypto/blake3/blake3.h+++ /dev/null@@ -1,86 +0,0 @@-#ifndef BLAKE3_H-#define BLAKE3_H--#include <stddef.h>-#include <stdint.h>--#if !defined(BLAKE3_API)-# if defined(_WIN32) || defined(__CYGWIN__)-# if defined(BLAKE3_DLL)-# if defined(BLAKE3_DLL_EXPORTS)-# define BLAKE3_API __declspec(dllexport)-# else-# define BLAKE3_API __declspec(dllimport)-# endif-# define BLAKE3_PRIVATE-# else-# define BLAKE3_API-# define BLAKE3_PRIVATE-# endif-# elif __GNUC__ >= 4-# define BLAKE3_API __attribute__((visibility("default")))-# define BLAKE3_PRIVATE __attribute__((visibility("hidden")))-# else-# define BLAKE3_API-# define BLAKE3_PRIVATE-# endif-#endif--#ifdef __cplusplus-extern "C" {-#endif--#define BLAKE3_VERSION_STRING "1.8.7"-#define BLAKE3_KEY_LEN 32-#define BLAKE3_OUT_LEN 32-#define BLAKE3_BLOCK_LEN 64-#define BLAKE3_CHUNK_LEN 1024-#define BLAKE3_MAX_DEPTH 54--// This struct is a private implementation detail. It has to be here because-// it's part of the blake3_hasher structure defined below.-typedef struct {- uint32_t cv[8];- uint64_t chunk_counter;- uint8_t buf[BLAKE3_BLOCK_LEN];- uint8_t buf_len;- uint8_t blocks_compressed;- uint8_t flags;-} blake3_chunk_state;--typedef struct {- uint32_t key[8];- blake3_chunk_state chunk;- uint8_t cv_stack_len;- // The stack size is MAX_DEPTH + 1 because we do lazy merging. For example,- // with 7 chunks, we have 3 entries in the stack. Adding an 8th chunk- // requires a 4th entry, rather than merging everything down to 1, because we- // don't know whether more input is coming. This is different from how the- // reference implementation does things.- uint8_t cv_stack[(BLAKE3_MAX_DEPTH + 1) * BLAKE3_OUT_LEN];-} blake3_hasher;--BLAKE3_API const char *blake3_version(void);-BLAKE3_API void blake3_hasher_init(blake3_hasher *self);-BLAKE3_API void blake3_hasher_init_keyed(blake3_hasher *self,- const uint8_t key[BLAKE3_KEY_LEN]);-BLAKE3_API void blake3_hasher_init_derive_key(blake3_hasher *self, const char *context);-BLAKE3_API void blake3_hasher_init_derive_key_raw(blake3_hasher *self, const void *context,- size_t context_len);-BLAKE3_API void blake3_hasher_update(blake3_hasher *self, const void *input,- size_t input_len);-#if defined(BLAKE3_USE_TBB)-BLAKE3_API void blake3_hasher_update_tbb(blake3_hasher *self, const void *input,- size_t input_len);-#endif // BLAKE3_USE_TBB-BLAKE3_API void blake3_hasher_finalize(const blake3_hasher *self, uint8_t *out,- size_t out_len);-BLAKE3_API void blake3_hasher_finalize_seek(const blake3_hasher *self, uint64_t seek,- uint8_t *out, size_t out_len);-BLAKE3_API void blake3_hasher_reset(blake3_hasher *self);--#ifdef __cplusplus-}-#endif--#endif /* BLAKE3_H */--- a/src/src/crypto/blake3/blake3_avx2.c+++ /dev/null@@ -1,326 +0,0 @@-#include "blake3_impl.h"--#include <immintrin.h>--#define DEGREE 8--INLINE __m256i loadu(const uint8_t src[32]) {- return _mm256_loadu_si256((const __m256i *)src);-}--INLINE void storeu(__m256i src, uint8_t dest[16]) {- _mm256_storeu_si256((__m256i *)dest, src);-}--INLINE __m256i addv(__m256i a, __m256i b) { return _mm256_add_epi32(a, b); }--// Note that clang-format doesn't like the name "xor" for some reason.-INLINE __m256i xorv(__m256i a, __m256i b) { return _mm256_xor_si256(a, b); }--INLINE __m256i set1(uint32_t x) { return _mm256_set1_epi32((int32_t)x); }--INLINE __m256i rot16(__m256i x) {- return _mm256_shuffle_epi8(- x, _mm256_set_epi8(13, 12, 15, 14, 9, 8, 11, 10, 5, 4, 7, 6, 1, 0, 3, 2,- 13, 12, 15, 14, 9, 8, 11, 10, 5, 4, 7, 6, 1, 0, 3, 2));-}--INLINE __m256i rot12(__m256i x) {- return _mm256_or_si256(_mm256_srli_epi32(x, 12), _mm256_slli_epi32(x, 32 - 12));-}--INLINE __m256i rot8(__m256i x) {- return _mm256_shuffle_epi8(- x, _mm256_set_epi8(12, 15, 14, 13, 8, 11, 10, 9, 4, 7, 6, 5, 0, 3, 2, 1,- 12, 15, 14, 13, 8, 11, 10, 9, 4, 7, 6, 5, 0, 3, 2, 1));-}--INLINE __m256i rot7(__m256i x) {- return _mm256_or_si256(_mm256_srli_epi32(x, 7), _mm256_slli_epi32(x, 32 - 7));-}--INLINE void round_fn(__m256i v[16], __m256i m[16], size_t r) {- v[0] = addv(v[0], m[(size_t)MSG_SCHEDULE[r][0]]);- v[1] = addv(v[1], m[(size_t)MSG_SCHEDULE[r][2]]);- v[2] = addv(v[2], m[(size_t)MSG_SCHEDULE[r][4]]);- v[3] = addv(v[3], m[(size_t)MSG_SCHEDULE[r][6]]);- v[0] = addv(v[0], v[4]);- v[1] = addv(v[1], v[5]);- v[2] = addv(v[2], v[6]);- v[3] = addv(v[3], v[7]);- v[12] = xorv(v[12], v[0]);- v[13] = xorv(v[13], v[1]);- v[14] = xorv(v[14], v[2]);- v[15] = xorv(v[15], v[3]);- v[12] = rot16(v[12]);- v[13] = rot16(v[13]);- v[14] = rot16(v[14]);- v[15] = rot16(v[15]);- v[8] = addv(v[8], v[12]);- v[9] = addv(v[9], v[13]);- v[10] = addv(v[10], v[14]);- v[11] = addv(v[11], v[15]);- v[4] = xorv(v[4], v[8]);- v[5] = xorv(v[5], v[9]);- v[6] = xorv(v[6], v[10]);- v[7] = xorv(v[7], v[11]);- v[4] = rot12(v[4]);- v[5] = rot12(v[5]);- v[6] = rot12(v[6]);- v[7] = rot12(v[7]);- v[0] = addv(v[0], m[(size_t)MSG_SCHEDULE[r][1]]);- v[1] = addv(v[1], m[(size_t)MSG_SCHEDULE[r][3]]);- v[2] = addv(v[2], m[(size_t)MSG_SCHEDULE[r][5]]);- v[3] = addv(v[3], m[(size_t)MSG_SCHEDULE[r][7]]);- v[0] = addv(v[0], v[4]);- v[1] = addv(v[1], v[5]);- v[2] = addv(v[2], v[6]);- v[3] = addv(v[3], v[7]);- v[12] = xorv(v[12], v[0]);- v[13] = xorv(v[13], v[1]);- v[14] = xorv(v[14], v[2]);- v[15] = xorv(v[15], v[3]);- v[12] = rot8(v[12]);- v[13] = rot8(v[13]);- v[14] = rot8(v[14]);- v[15] = rot8(v[15]);- v[8] = addv(v[8], v[12]);- v[9] = addv(v[9], v[13]);- v[10] = addv(v[10], v[14]);- v[11] = addv(v[11], v[15]);- v[4] = xorv(v[4], v[8]);- v[5] = xorv(v[5], v[9]);- v[6] = xorv(v[6], v[10]);- v[7] = xorv(v[7], v[11]);- v[4] = rot7(v[4]);- v[5] = rot7(v[5]);- v[6] = rot7(v[6]);- v[7] = rot7(v[7]);-- v[0] = addv(v[0], m[(size_t)MSG_SCHEDULE[r][8]]);- v[1] = addv(v[1], m[(size_t)MSG_SCHEDULE[r][10]]);- v[2] = addv(v[2], m[(size_t)MSG_SCHEDULE[r][12]]);- v[3] = addv(v[3], m[(size_t)MSG_SCHEDULE[r][14]]);- v[0] = addv(v[0], v[5]);- v[1] = addv(v[1], v[6]);- v[2] = addv(v[2], v[7]);- v[3] = addv(v[3], v[4]);- v[15] = xorv(v[15], v[0]);- v[12] = xorv(v[12], v[1]);- v[13] = xorv(v[13], v[2]);- v[14] = xorv(v[14], v[3]);- v[15] = rot16(v[15]);- v[12] = rot16(v[12]);- v[13] = rot16(v[13]);- v[14] = rot16(v[14]);- v[10] = addv(v[10], v[15]);- v[11] = addv(v[11], v[12]);- v[8] = addv(v[8], v[13]);- v[9] = addv(v[9], v[14]);- v[5] = xorv(v[5], v[10]);- v[6] = xorv(v[6], v[11]);- v[7] = xorv(v[7], v[8]);- v[4] = xorv(v[4], v[9]);- v[5] = rot12(v[5]);- v[6] = rot12(v[6]);- v[7] = rot12(v[7]);- v[4] = rot12(v[4]);- v[0] = addv(v[0], m[(size_t)MSG_SCHEDULE[r][9]]);- v[1] = addv(v[1], m[(size_t)MSG_SCHEDULE[r][11]]);- v[2] = addv(v[2], m[(size_t)MSG_SCHEDULE[r][13]]);- v[3] = addv(v[3], m[(size_t)MSG_SCHEDULE[r][15]]);- v[0] = addv(v[0], v[5]);- v[1] = addv(v[1], v[6]);- v[2] = addv(v[2], v[7]);- v[3] = addv(v[3], v[4]);- v[15] = xorv(v[15], v[0]);- v[12] = xorv(v[12], v[1]);- v[13] = xorv(v[13], v[2]);- v[14] = xorv(v[14], v[3]);- v[15] = rot8(v[15]);- v[12] = rot8(v[12]);- v[13] = rot8(v[13]);- v[14] = rot8(v[14]);- v[10] = addv(v[10], v[15]);- v[11] = addv(v[11], v[12]);- v[8] = addv(v[8], v[13]);- v[9] = addv(v[9], v[14]);- v[5] = xorv(v[5], v[10]);- v[6] = xorv(v[6], v[11]);- v[7] = xorv(v[7], v[8]);- v[4] = xorv(v[4], v[9]);- v[5] = rot7(v[5]);- v[6] = rot7(v[6]);- v[7] = rot7(v[7]);- v[4] = rot7(v[4]);-}--INLINE void transpose_vecs(__m256i vecs[DEGREE]) {- // Interleave 32-bit lanes. The low unpack is lanes 00/11/44/55, and the high- // is 22/33/66/77.- __m256i ab_0145 = _mm256_unpacklo_epi32(vecs[0], vecs[1]);- __m256i ab_2367 = _mm256_unpackhi_epi32(vecs[0], vecs[1]);- __m256i cd_0145 = _mm256_unpacklo_epi32(vecs[2], vecs[3]);- __m256i cd_2367 = _mm256_unpackhi_epi32(vecs[2], vecs[3]);- __m256i ef_0145 = _mm256_unpacklo_epi32(vecs[4], vecs[5]);- __m256i ef_2367 = _mm256_unpackhi_epi32(vecs[4], vecs[5]);- __m256i gh_0145 = _mm256_unpacklo_epi32(vecs[6], vecs[7]);- __m256i gh_2367 = _mm256_unpackhi_epi32(vecs[6], vecs[7]);-- // Interleave 64-bit lanes. The low unpack is lanes 00/22 and the high is- // 11/33.- __m256i abcd_04 = _mm256_unpacklo_epi64(ab_0145, cd_0145);- __m256i abcd_15 = _mm256_unpackhi_epi64(ab_0145, cd_0145);- __m256i abcd_26 = _mm256_unpacklo_epi64(ab_2367, cd_2367);- __m256i abcd_37 = _mm256_unpackhi_epi64(ab_2367, cd_2367);- __m256i efgh_04 = _mm256_unpacklo_epi64(ef_0145, gh_0145);- __m256i efgh_15 = _mm256_unpackhi_epi64(ef_0145, gh_0145);- __m256i efgh_26 = _mm256_unpacklo_epi64(ef_2367, gh_2367);- __m256i efgh_37 = _mm256_unpackhi_epi64(ef_2367, gh_2367);-- // Interleave 128-bit lanes.- vecs[0] = _mm256_permute2x128_si256(abcd_04, efgh_04, 0x20);- vecs[1] = _mm256_permute2x128_si256(abcd_15, efgh_15, 0x20);- vecs[2] = _mm256_permute2x128_si256(abcd_26, efgh_26, 0x20);- vecs[3] = _mm256_permute2x128_si256(abcd_37, efgh_37, 0x20);- vecs[4] = _mm256_permute2x128_si256(abcd_04, efgh_04, 0x31);- vecs[5] = _mm256_permute2x128_si256(abcd_15, efgh_15, 0x31);- vecs[6] = _mm256_permute2x128_si256(abcd_26, efgh_26, 0x31);- vecs[7] = _mm256_permute2x128_si256(abcd_37, efgh_37, 0x31);-}--INLINE void transpose_msg_vecs(const uint8_t *const *inputs,- size_t block_offset, __m256i out[16]) {- out[0] = loadu(&inputs[0][block_offset + 0 * sizeof(__m256i)]);- out[1] = loadu(&inputs[1][block_offset + 0 * sizeof(__m256i)]);- out[2] = loadu(&inputs[2][block_offset + 0 * sizeof(__m256i)]);- out[3] = loadu(&inputs[3][block_offset + 0 * sizeof(__m256i)]);- out[4] = loadu(&inputs[4][block_offset + 0 * sizeof(__m256i)]);- out[5] = loadu(&inputs[5][block_offset + 0 * sizeof(__m256i)]);- out[6] = loadu(&inputs[6][block_offset + 0 * sizeof(__m256i)]);- out[7] = loadu(&inputs[7][block_offset + 0 * sizeof(__m256i)]);- out[8] = loadu(&inputs[0][block_offset + 1 * sizeof(__m256i)]);- out[9] = loadu(&inputs[1][block_offset + 1 * sizeof(__m256i)]);- out[10] = loadu(&inputs[2][block_offset + 1 * sizeof(__m256i)]);- out[11] = loadu(&inputs[3][block_offset + 1 * sizeof(__m256i)]);- out[12] = loadu(&inputs[4][block_offset + 1 * sizeof(__m256i)]);- out[13] = loadu(&inputs[5][block_offset + 1 * sizeof(__m256i)]);- out[14] = loadu(&inputs[6][block_offset + 1 * sizeof(__m256i)]);- out[15] = loadu(&inputs[7][block_offset + 1 * sizeof(__m256i)]);- for (size_t i = 0; i < 8; ++i) {- _mm_prefetch((const void *)&inputs[i][block_offset + 256], _MM_HINT_T0);- }- transpose_vecs(&out[0]);- transpose_vecs(&out[8]);-}--INLINE void load_counters(uint64_t counter, bool increment_counter,- __m256i *out_lo, __m256i *out_hi) {- const __m256i mask = _mm256_set1_epi32(-(int32_t)increment_counter);- const __m256i add0 = _mm256_set_epi32(7, 6, 5, 4, 3, 2, 1, 0);- const __m256i add1 = _mm256_and_si256(mask, add0);- __m256i l = _mm256_add_epi32(_mm256_set1_epi32((int32_t)counter), add1);- __m256i carry = _mm256_cmpgt_epi32(_mm256_xor_si256(add1, _mm256_set1_epi32(0x80000000)), - _mm256_xor_si256( l, _mm256_set1_epi32(0x80000000)));- __m256i h = _mm256_sub_epi32(_mm256_set1_epi32((int32_t)(counter >> 32)), carry);- *out_lo = l;- *out_hi = h;-}--static-void blake3_hash8_avx2(const uint8_t *const *inputs, size_t blocks,- const uint32_t key[8], uint64_t counter,- bool increment_counter, uint8_t flags,- uint8_t flags_start, uint8_t flags_end, uint8_t *out) {- __m256i h_vecs[8] = {- set1(key[0]), set1(key[1]), set1(key[2]), set1(key[3]),- set1(key[4]), set1(key[5]), set1(key[6]), set1(key[7]),- };- __m256i counter_low_vec, counter_high_vec;- load_counters(counter, increment_counter, &counter_low_vec,- &counter_high_vec);- uint8_t block_flags = flags | flags_start;-- for (size_t block = 0; block < blocks; block++) {- if (block + 1 == blocks) {- block_flags |= flags_end;- }- __m256i block_len_vec = set1(BLAKE3_BLOCK_LEN);- __m256i block_flags_vec = set1(block_flags);- __m256i msg_vecs[16];- transpose_msg_vecs(inputs, block * BLAKE3_BLOCK_LEN, msg_vecs);-- __m256i v[16] = {- h_vecs[0], h_vecs[1], h_vecs[2], h_vecs[3],- h_vecs[4], h_vecs[5], h_vecs[6], h_vecs[7],- set1(IV[0]), set1(IV[1]), set1(IV[2]), set1(IV[3]),- counter_low_vec, counter_high_vec, block_len_vec, block_flags_vec,- };- round_fn(v, msg_vecs, 0);- round_fn(v, msg_vecs, 1);- round_fn(v, msg_vecs, 2);- round_fn(v, msg_vecs, 3);- round_fn(v, msg_vecs, 4);- round_fn(v, msg_vecs, 5);- round_fn(v, msg_vecs, 6);- h_vecs[0] = xorv(v[0], v[8]);- h_vecs[1] = xorv(v[1], v[9]);- h_vecs[2] = xorv(v[2], v[10]);- h_vecs[3] = xorv(v[3], v[11]);- h_vecs[4] = xorv(v[4], v[12]);- h_vecs[5] = xorv(v[5], v[13]);- h_vecs[6] = xorv(v[6], v[14]);- h_vecs[7] = xorv(v[7], v[15]);-- block_flags = flags;- }-- transpose_vecs(h_vecs);- storeu(h_vecs[0], &out[0 * sizeof(__m256i)]);- storeu(h_vecs[1], &out[1 * sizeof(__m256i)]);- storeu(h_vecs[2], &out[2 * sizeof(__m256i)]);- storeu(h_vecs[3], &out[3 * sizeof(__m256i)]);- storeu(h_vecs[4], &out[4 * sizeof(__m256i)]);- storeu(h_vecs[5], &out[5 * sizeof(__m256i)]);- storeu(h_vecs[6], &out[6 * sizeof(__m256i)]);- storeu(h_vecs[7], &out[7 * sizeof(__m256i)]);-}--#if !defined(BLAKE3_NO_SSE41)-void blake3_hash_many_sse41(const uint8_t *const *inputs, size_t num_inputs,- size_t blocks, const uint32_t key[8],- uint64_t counter, bool increment_counter,- uint8_t flags, uint8_t flags_start,- uint8_t flags_end, uint8_t *out);-#else-void blake3_hash_many_portable(const uint8_t *const *inputs, size_t num_inputs,- size_t blocks, const uint32_t key[8],- uint64_t counter, bool increment_counter,- uint8_t flags, uint8_t flags_start,- uint8_t flags_end, uint8_t *out);-#endif--void blake3_hash_many_avx2(const uint8_t *const *inputs, size_t num_inputs,- size_t blocks, const uint32_t key[8],- uint64_t counter, bool increment_counter,- uint8_t flags, uint8_t flags_start,- uint8_t flags_end, uint8_t *out) {- while (num_inputs >= DEGREE) {- blake3_hash8_avx2(inputs, blocks, key, counter, increment_counter, flags,- flags_start, flags_end, out);- if (increment_counter) {- counter += DEGREE;- }- inputs += DEGREE;- num_inputs -= DEGREE;- out = &out[DEGREE * BLAKE3_OUT_LEN];- }-#if !defined(BLAKE3_NO_SSE41)- blake3_hash_many_sse41(inputs, num_inputs, blocks, key, counter,- increment_counter, flags, flags_start, flags_end, out);-#else- blake3_hash_many_portable(inputs, num_inputs, blocks, key, counter,- increment_counter, flags, flags_start, flags_end,- out);-#endif-}--- a/src/src/crypto/blake3/blake3_avx512.c+++ /dev/null@@ -1,1388 +0,0 @@-#include "blake3_impl.h"--#include <immintrin.h>--#define _mm_shuffle_ps2(a, b, c) \- (_mm_castps_si128( \- _mm_shuffle_ps(_mm_castsi128_ps(a), _mm_castsi128_ps(b), (c))))--INLINE __m128i loadu_128(const uint8_t src[16]) {- return _mm_loadu_si128((void*)src);-}--INLINE __m256i loadu_256(const uint8_t src[32]) {- return _mm256_loadu_si256((void*)src);-}--INLINE __m512i loadu_512(const uint8_t src[64]) {- return _mm512_loadu_si512((void*)src);-}--INLINE void storeu_128(__m128i src, uint8_t dest[16]) {- _mm_storeu_si128((void*)dest, src);-}--INLINE void storeu_256(__m256i src, uint8_t dest[16]) {- _mm256_storeu_si256((void*)dest, src);-}--INLINE void storeu_512(__m512i src, uint8_t dest[16]) {- _mm512_storeu_si512((void*)dest, src);-}--INLINE __m128i add_128(__m128i a, __m128i b) { return _mm_add_epi32(a, b); }--INLINE __m256i add_256(__m256i a, __m256i b) { return _mm256_add_epi32(a, b); }--INLINE __m512i add_512(__m512i a, __m512i b) { return _mm512_add_epi32(a, b); }--INLINE __m128i xor_128(__m128i a, __m128i b) { return _mm_xor_si128(a, b); }--INLINE __m256i xor_256(__m256i a, __m256i b) { return _mm256_xor_si256(a, b); }--INLINE __m512i xor_512(__m512i a, __m512i b) { return _mm512_xor_si512(a, b); }--INLINE __m128i set1_128(uint32_t x) { return _mm_set1_epi32((int32_t)x); }--INLINE __m256i set1_256(uint32_t x) { return _mm256_set1_epi32((int32_t)x); }--INLINE __m512i set1_512(uint32_t x) { return _mm512_set1_epi32((int32_t)x); }--INLINE __m128i set4(uint32_t a, uint32_t b, uint32_t c, uint32_t d) {- return _mm_setr_epi32((int32_t)a, (int32_t)b, (int32_t)c, (int32_t)d);-}--INLINE __m128i rot16_128(__m128i x) { return _mm_ror_epi32(x, 16); }--INLINE __m256i rot16_256(__m256i x) { return _mm256_ror_epi32(x, 16); }--INLINE __m512i rot16_512(__m512i x) { return _mm512_ror_epi32(x, 16); }--INLINE __m128i rot12_128(__m128i x) { return _mm_ror_epi32(x, 12); }--INLINE __m256i rot12_256(__m256i x) { return _mm256_ror_epi32(x, 12); }--INLINE __m512i rot12_512(__m512i x) { return _mm512_ror_epi32(x, 12); }--INLINE __m128i rot8_128(__m128i x) { return _mm_ror_epi32(x, 8); }--INLINE __m256i rot8_256(__m256i x) { return _mm256_ror_epi32(x, 8); }--INLINE __m512i rot8_512(__m512i x) { return _mm512_ror_epi32(x, 8); }--INLINE __m128i rot7_128(__m128i x) { return _mm_ror_epi32(x, 7); }--INLINE __m256i rot7_256(__m256i x) { return _mm256_ror_epi32(x, 7); }--INLINE __m512i rot7_512(__m512i x) { return _mm512_ror_epi32(x, 7); }--/*- * ----------------------------------------------------------------------------- * compress_avx512- * ----------------------------------------------------------------------------- */--INLINE void g1(__m128i *row0, __m128i *row1, __m128i *row2, __m128i *row3,- __m128i m) {- *row0 = add_128(add_128(*row0, m), *row1);- *row3 = xor_128(*row3, *row0);- *row3 = rot16_128(*row3);- *row2 = add_128(*row2, *row3);- *row1 = xor_128(*row1, *row2);- *row1 = rot12_128(*row1);-}--INLINE void g2(__m128i *row0, __m128i *row1, __m128i *row2, __m128i *row3,- __m128i m) {- *row0 = add_128(add_128(*row0, m), *row1);- *row3 = xor_128(*row3, *row0);- *row3 = rot8_128(*row3);- *row2 = add_128(*row2, *row3);- *row1 = xor_128(*row1, *row2);- *row1 = rot7_128(*row1);-}--// Note the optimization here of leaving row1 as the unrotated row, rather than-// row0. All the message loads below are adjusted to compensate for this. See-// discussion at https://github.com/sneves/blake2-avx2/pull/4-INLINE void diagonalize(__m128i *row0, __m128i *row2, __m128i *row3) {- *row0 = _mm_shuffle_epi32(*row0, _MM_SHUFFLE(2, 1, 0, 3));- *row3 = _mm_shuffle_epi32(*row3, _MM_SHUFFLE(1, 0, 3, 2));- *row2 = _mm_shuffle_epi32(*row2, _MM_SHUFFLE(0, 3, 2, 1));-}--INLINE void undiagonalize(__m128i *row0, __m128i *row2, __m128i *row3) {- *row0 = _mm_shuffle_epi32(*row0, _MM_SHUFFLE(0, 3, 2, 1));- *row3 = _mm_shuffle_epi32(*row3, _MM_SHUFFLE(1, 0, 3, 2));- *row2 = _mm_shuffle_epi32(*row2, _MM_SHUFFLE(2, 1, 0, 3));-}--INLINE void compress_pre(__m128i rows[4], const uint32_t cv[8],- const uint8_t block[BLAKE3_BLOCK_LEN],- uint8_t block_len, uint64_t counter, uint8_t flags) {- rows[0] = loadu_128((uint8_t *)&cv[0]);- rows[1] = loadu_128((uint8_t *)&cv[4]);- rows[2] = set4(IV[0], IV[1], IV[2], IV[3]);- rows[3] = set4(counter_low(counter), counter_high(counter),- (uint32_t)block_len, (uint32_t)flags);-- __m128i m0 = loadu_128(&block[sizeof(__m128i) * 0]);- __m128i m1 = loadu_128(&block[sizeof(__m128i) * 1]);- __m128i m2 = loadu_128(&block[sizeof(__m128i) * 2]);- __m128i m3 = loadu_128(&block[sizeof(__m128i) * 3]);-- __m128i t0, t1, t2, t3, tt;-- // Round 1. The first round permutes the message words from the original- // input order, into the groups that get mixed in parallel.- t0 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(2, 0, 2, 0)); // 6 4 2 0- g1(&rows[0], &rows[1], &rows[2], &rows[3], t0);- t1 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(3, 1, 3, 1)); // 7 5 3 1- g2(&rows[0], &rows[1], &rows[2], &rows[3], t1);- diagonalize(&rows[0], &rows[2], &rows[3]);- t2 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(2, 0, 2, 0)); // 14 12 10 8- t2 = _mm_shuffle_epi32(t2, _MM_SHUFFLE(2, 1, 0, 3)); // 12 10 8 14- g1(&rows[0], &rows[1], &rows[2], &rows[3], t2);- t3 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(3, 1, 3, 1)); // 15 13 11 9- t3 = _mm_shuffle_epi32(t3, _MM_SHUFFLE(2, 1, 0, 3)); // 13 11 9 15- g2(&rows[0], &rows[1], &rows[2], &rows[3], t3);- undiagonalize(&rows[0], &rows[2], &rows[3]);- m0 = t0;- m1 = t1;- m2 = t2;- m3 = t3;-- // Round 2. This round and all following rounds apply a fixed permutation- // to the message words from the round before.- t0 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(3, 1, 1, 2));- t0 = _mm_shuffle_epi32(t0, _MM_SHUFFLE(0, 3, 2, 1));- g1(&rows[0], &rows[1], &rows[2], &rows[3], t0);- t1 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(3, 3, 2, 2));- tt = _mm_shuffle_epi32(m0, _MM_SHUFFLE(0, 0, 3, 3));- t1 = _mm_blend_epi16(tt, t1, 0xCC);- g2(&rows[0], &rows[1], &rows[2], &rows[3], t1);- diagonalize(&rows[0], &rows[2], &rows[3]);- t2 = _mm_unpacklo_epi64(m3, m1);- tt = _mm_blend_epi16(t2, m2, 0xC0);- t2 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(1, 3, 2, 0));- g1(&rows[0], &rows[1], &rows[2], &rows[3], t2);- t3 = _mm_unpackhi_epi32(m1, m3);- tt = _mm_unpacklo_epi32(m2, t3);- t3 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(0, 1, 3, 2));- g2(&rows[0], &rows[1], &rows[2], &rows[3], t3);- undiagonalize(&rows[0], &rows[2], &rows[3]);- m0 = t0;- m1 = t1;- m2 = t2;- m3 = t3;-- // Round 3- t0 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(3, 1, 1, 2));- t0 = _mm_shuffle_epi32(t0, _MM_SHUFFLE(0, 3, 2, 1));- g1(&rows[0], &rows[1], &rows[2], &rows[3], t0);- t1 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(3, 3, 2, 2));- tt = _mm_shuffle_epi32(m0, _MM_SHUFFLE(0, 0, 3, 3));- t1 = _mm_blend_epi16(tt, t1, 0xCC);- g2(&rows[0], &rows[1], &rows[2], &rows[3], t1);- diagonalize(&rows[0], &rows[2], &rows[3]);- t2 = _mm_unpacklo_epi64(m3, m1);- tt = _mm_blend_epi16(t2, m2, 0xC0);- t2 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(1, 3, 2, 0));- g1(&rows[0], &rows[1], &rows[2], &rows[3], t2);- t3 = _mm_unpackhi_epi32(m1, m3);- tt = _mm_unpacklo_epi32(m2, t3);- t3 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(0, 1, 3, 2));- g2(&rows[0], &rows[1], &rows[2], &rows[3], t3);- undiagonalize(&rows[0], &rows[2], &rows[3]);- m0 = t0;- m1 = t1;- m2 = t2;- m3 = t3;-- // Round 4- t0 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(3, 1, 1, 2));- t0 = _mm_shuffle_epi32(t0, _MM_SHUFFLE(0, 3, 2, 1));- g1(&rows[0], &rows[1], &rows[2], &rows[3], t0);- t1 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(3, 3, 2, 2));- tt = _mm_shuffle_epi32(m0, _MM_SHUFFLE(0, 0, 3, 3));- t1 = _mm_blend_epi16(tt, t1, 0xCC);- g2(&rows[0], &rows[1], &rows[2], &rows[3], t1);- diagonalize(&rows[0], &rows[2], &rows[3]);- t2 = _mm_unpacklo_epi64(m3, m1);- tt = _mm_blend_epi16(t2, m2, 0xC0);- t2 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(1, 3, 2, 0));- g1(&rows[0], &rows[1], &rows[2], &rows[3], t2);- t3 = _mm_unpackhi_epi32(m1, m3);- tt = _mm_unpacklo_epi32(m2, t3);- t3 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(0, 1, 3, 2));- g2(&rows[0], &rows[1], &rows[2], &rows[3], t3);- undiagonalize(&rows[0], &rows[2], &rows[3]);- m0 = t0;- m1 = t1;- m2 = t2;- m3 = t3;-- // Round 5- t0 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(3, 1, 1, 2));- t0 = _mm_shuffle_epi32(t0, _MM_SHUFFLE(0, 3, 2, 1));- g1(&rows[0], &rows[1], &rows[2], &rows[3], t0);- t1 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(3, 3, 2, 2));- tt = _mm_shuffle_epi32(m0, _MM_SHUFFLE(0, 0, 3, 3));- t1 = _mm_blend_epi16(tt, t1, 0xCC);- g2(&rows[0], &rows[1], &rows[2], &rows[3], t1);- diagonalize(&rows[0], &rows[2], &rows[3]);- t2 = _mm_unpacklo_epi64(m3, m1);- tt = _mm_blend_epi16(t2, m2, 0xC0);- t2 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(1, 3, 2, 0));- g1(&rows[0], &rows[1], &rows[2], &rows[3], t2);- t3 = _mm_unpackhi_epi32(m1, m3);- tt = _mm_unpacklo_epi32(m2, t3);- t3 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(0, 1, 3, 2));- g2(&rows[0], &rows[1], &rows[2], &rows[3], t3);- undiagonalize(&rows[0], &rows[2], &rows[3]);- m0 = t0;- m1 = t1;- m2 = t2;- m3 = t3;-- // Round 6- t0 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(3, 1, 1, 2));- t0 = _mm_shuffle_epi32(t0, _MM_SHUFFLE(0, 3, 2, 1));- g1(&rows[0], &rows[1], &rows[2], &rows[3], t0);- t1 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(3, 3, 2, 2));- tt = _mm_shuffle_epi32(m0, _MM_SHUFFLE(0, 0, 3, 3));- t1 = _mm_blend_epi16(tt, t1, 0xCC);- g2(&rows[0], &rows[1], &rows[2], &rows[3], t1);- diagonalize(&rows[0], &rows[2], &rows[3]);- t2 = _mm_unpacklo_epi64(m3, m1);- tt = _mm_blend_epi16(t2, m2, 0xC0);- t2 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(1, 3, 2, 0));- g1(&rows[0], &rows[1], &rows[2], &rows[3], t2);- t3 = _mm_unpackhi_epi32(m1, m3);- tt = _mm_unpacklo_epi32(m2, t3);- t3 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(0, 1, 3, 2));- g2(&rows[0], &rows[1], &rows[2], &rows[3], t3);- undiagonalize(&rows[0], &rows[2], &rows[3]);- m0 = t0;- m1 = t1;- m2 = t2;- m3 = t3;-- // Round 7- t0 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(3, 1, 1, 2));- t0 = _mm_shuffle_epi32(t0, _MM_SHUFFLE(0, 3, 2, 1));- g1(&rows[0], &rows[1], &rows[2], &rows[3], t0);- t1 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(3, 3, 2, 2));- tt = _mm_shuffle_epi32(m0, _MM_SHUFFLE(0, 0, 3, 3));- t1 = _mm_blend_epi16(tt, t1, 0xCC);- g2(&rows[0], &rows[1], &rows[2], &rows[3], t1);- diagonalize(&rows[0], &rows[2], &rows[3]);- t2 = _mm_unpacklo_epi64(m3, m1);- tt = _mm_blend_epi16(t2, m2, 0xC0);- t2 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(1, 3, 2, 0));- g1(&rows[0], &rows[1], &rows[2], &rows[3], t2);- t3 = _mm_unpackhi_epi32(m1, m3);- tt = _mm_unpacklo_epi32(m2, t3);- t3 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(0, 1, 3, 2));- g2(&rows[0], &rows[1], &rows[2], &rows[3], t3);- undiagonalize(&rows[0], &rows[2], &rows[3]);-}--void blake3_compress_xof_avx512(const uint32_t cv[8],- const uint8_t block[BLAKE3_BLOCK_LEN],- uint8_t block_len, uint64_t counter,- uint8_t flags, uint8_t out[64]) {- __m128i rows[4];- compress_pre(rows, cv, block, block_len, counter, flags);- storeu_128(xor_128(rows[0], rows[2]), &out[0]);- storeu_128(xor_128(rows[1], rows[3]), &out[16]);- storeu_128(xor_128(rows[2], loadu_128((uint8_t *)&cv[0])), &out[32]);- storeu_128(xor_128(rows[3], loadu_128((uint8_t *)&cv[4])), &out[48]);-}--void blake3_compress_in_place_avx512(uint32_t cv[8],- const uint8_t block[BLAKE3_BLOCK_LEN],- uint8_t block_len, uint64_t counter,- uint8_t flags) {- __m128i rows[4];- compress_pre(rows, cv, block, block_len, counter, flags);- storeu_128(xor_128(rows[0], rows[2]), (uint8_t *)&cv[0]);- storeu_128(xor_128(rows[1], rows[3]), (uint8_t *)&cv[4]);-}--/*- * ----------------------------------------------------------------------------- * hash4_avx512- * ----------------------------------------------------------------------------- */--INLINE void round_fn4(__m128i v[16], __m128i m[16], size_t r) {- v[0] = add_128(v[0], m[(size_t)MSG_SCHEDULE[r][0]]);- v[1] = add_128(v[1], m[(size_t)MSG_SCHEDULE[r][2]]);- v[2] = add_128(v[2], m[(size_t)MSG_SCHEDULE[r][4]]);- v[3] = add_128(v[3], m[(size_t)MSG_SCHEDULE[r][6]]);- v[0] = add_128(v[0], v[4]);- v[1] = add_128(v[1], v[5]);- v[2] = add_128(v[2], v[6]);- v[3] = add_128(v[3], v[7]);- v[12] = xor_128(v[12], v[0]);- v[13] = xor_128(v[13], v[1]);- v[14] = xor_128(v[14], v[2]);- v[15] = xor_128(v[15], v[3]);- v[12] = rot16_128(v[12]);- v[13] = rot16_128(v[13]);- v[14] = rot16_128(v[14]);- v[15] = rot16_128(v[15]);- v[8] = add_128(v[8], v[12]);- v[9] = add_128(v[9], v[13]);- v[10] = add_128(v[10], v[14]);- v[11] = add_128(v[11], v[15]);- v[4] = xor_128(v[4], v[8]);- v[5] = xor_128(v[5], v[9]);- v[6] = xor_128(v[6], v[10]);- v[7] = xor_128(v[7], v[11]);- v[4] = rot12_128(v[4]);- v[5] = rot12_128(v[5]);- v[6] = rot12_128(v[6]);- v[7] = rot12_128(v[7]);- v[0] = add_128(v[0], m[(size_t)MSG_SCHEDULE[r][1]]);- v[1] = add_128(v[1], m[(size_t)MSG_SCHEDULE[r][3]]);- v[2] = add_128(v[2], m[(size_t)MSG_SCHEDULE[r][5]]);- v[3] = add_128(v[3], m[(size_t)MSG_SCHEDULE[r][7]]);- v[0] = add_128(v[0], v[4]);- v[1] = add_128(v[1], v[5]);- v[2] = add_128(v[2], v[6]);- v[3] = add_128(v[3], v[7]);- v[12] = xor_128(v[12], v[0]);- v[13] = xor_128(v[13], v[1]);- v[14] = xor_128(v[14], v[2]);- v[15] = xor_128(v[15], v[3]);- v[12] = rot8_128(v[12]);- v[13] = rot8_128(v[13]);- v[14] = rot8_128(v[14]);- v[15] = rot8_128(v[15]);- v[8] = add_128(v[8], v[12]);- v[9] = add_128(v[9], v[13]);- v[10] = add_128(v[10], v[14]);- v[11] = add_128(v[11], v[15]);- v[4] = xor_128(v[4], v[8]);- v[5] = xor_128(v[5], v[9]);- v[6] = xor_128(v[6], v[10]);- v[7] = xor_128(v[7], v[11]);- v[4] = rot7_128(v[4]);- v[5] = rot7_128(v[5]);- v[6] = rot7_128(v[6]);- v[7] = rot7_128(v[7]);-- v[0] = add_128(v[0], m[(size_t)MSG_SCHEDULE[r][8]]);- v[1] = add_128(v[1], m[(size_t)MSG_SCHEDULE[r][10]]);- v[2] = add_128(v[2], m[(size_t)MSG_SCHEDULE[r][12]]);- v[3] = add_128(v[3], m[(size_t)MSG_SCHEDULE[r][14]]);- v[0] = add_128(v[0], v[5]);- v[1] = add_128(v[1], v[6]);- v[2] = add_128(v[2], v[7]);- v[3] = add_128(v[3], v[4]);- v[15] = xor_128(v[15], v[0]);- v[12] = xor_128(v[12], v[1]);- v[13] = xor_128(v[13], v[2]);- v[14] = xor_128(v[14], v[3]);- v[15] = rot16_128(v[15]);- v[12] = rot16_128(v[12]);- v[13] = rot16_128(v[13]);- v[14] = rot16_128(v[14]);- v[10] = add_128(v[10], v[15]);- v[11] = add_128(v[11], v[12]);- v[8] = add_128(v[8], v[13]);- v[9] = add_128(v[9], v[14]);- v[5] = xor_128(v[5], v[10]);- v[6] = xor_128(v[6], v[11]);- v[7] = xor_128(v[7], v[8]);- v[4] = xor_128(v[4], v[9]);- v[5] = rot12_128(v[5]);- v[6] = rot12_128(v[6]);- v[7] = rot12_128(v[7]);- v[4] = rot12_128(v[4]);- v[0] = add_128(v[0], m[(size_t)MSG_SCHEDULE[r][9]]);- v[1] = add_128(v[1], m[(size_t)MSG_SCHEDULE[r][11]]);- v[2] = add_128(v[2], m[(size_t)MSG_SCHEDULE[r][13]]);- v[3] = add_128(v[3], m[(size_t)MSG_SCHEDULE[r][15]]);- v[0] = add_128(v[0], v[5]);- v[1] = add_128(v[1], v[6]);- v[2] = add_128(v[2], v[7]);- v[3] = add_128(v[3], v[4]);- v[15] = xor_128(v[15], v[0]);- v[12] = xor_128(v[12], v[1]);- v[13] = xor_128(v[13], v[2]);- v[14] = xor_128(v[14], v[3]);- v[15] = rot8_128(v[15]);- v[12] = rot8_128(v[12]);- v[13] = rot8_128(v[13]);- v[14] = rot8_128(v[14]);- v[10] = add_128(v[10], v[15]);- v[11] = add_128(v[11], v[12]);- v[8] = add_128(v[8], v[13]);- v[9] = add_128(v[9], v[14]);- v[5] = xor_128(v[5], v[10]);- v[6] = xor_128(v[6], v[11]);- v[7] = xor_128(v[7], v[8]);- v[4] = xor_128(v[4], v[9]);- v[5] = rot7_128(v[5]);- v[6] = rot7_128(v[6]);- v[7] = rot7_128(v[7]);- v[4] = rot7_128(v[4]);-}--INLINE void transpose_vecs_128(__m128i vecs[4]) {- // Interleave 32-bit lanes. The low unpack is lanes 00/11 and the high is- // 22/33. Note that this doesn't split the vector into two lanes, as the- // AVX2 counterparts do.- __m128i ab_01 = _mm_unpacklo_epi32(vecs[0], vecs[1]);- __m128i ab_23 = _mm_unpackhi_epi32(vecs[0], vecs[1]);- __m128i cd_01 = _mm_unpacklo_epi32(vecs[2], vecs[3]);- __m128i cd_23 = _mm_unpackhi_epi32(vecs[2], vecs[3]);-- // Interleave 64-bit lanes.- __m128i abcd_0 = _mm_unpacklo_epi64(ab_01, cd_01);- __m128i abcd_1 = _mm_unpackhi_epi64(ab_01, cd_01);- __m128i abcd_2 = _mm_unpacklo_epi64(ab_23, cd_23);- __m128i abcd_3 = _mm_unpackhi_epi64(ab_23, cd_23);-- vecs[0] = abcd_0;- vecs[1] = abcd_1;- vecs[2] = abcd_2;- vecs[3] = abcd_3;-}--INLINE void transpose_msg_vecs4(const uint8_t *const *inputs,- size_t block_offset, __m128i out[16]) {- out[0] = loadu_128(&inputs[0][block_offset + 0 * sizeof(__m128i)]);- out[1] = loadu_128(&inputs[1][block_offset + 0 * sizeof(__m128i)]);- out[2] = loadu_128(&inputs[2][block_offset + 0 * sizeof(__m128i)]);- out[3] = loadu_128(&inputs[3][block_offset + 0 * sizeof(__m128i)]);- out[4] = loadu_128(&inputs[0][block_offset + 1 * sizeof(__m128i)]);- out[5] = loadu_128(&inputs[1][block_offset + 1 * sizeof(__m128i)]);- out[6] = loadu_128(&inputs[2][block_offset + 1 * sizeof(__m128i)]);- out[7] = loadu_128(&inputs[3][block_offset + 1 * sizeof(__m128i)]);- out[8] = loadu_128(&inputs[0][block_offset + 2 * sizeof(__m128i)]);- out[9] = loadu_128(&inputs[1][block_offset + 2 * sizeof(__m128i)]);- out[10] = loadu_128(&inputs[2][block_offset + 2 * sizeof(__m128i)]);- out[11] = loadu_128(&inputs[3][block_offset + 2 * sizeof(__m128i)]);- out[12] = loadu_128(&inputs[0][block_offset + 3 * sizeof(__m128i)]);- out[13] = loadu_128(&inputs[1][block_offset + 3 * sizeof(__m128i)]);- out[14] = loadu_128(&inputs[2][block_offset + 3 * sizeof(__m128i)]);- out[15] = loadu_128(&inputs[3][block_offset + 3 * sizeof(__m128i)]);- for (size_t i = 0; i < 4; ++i) {- _mm_prefetch((const void *)&inputs[i][block_offset + 256], _MM_HINT_T0);- }- transpose_vecs_128(&out[0]);- transpose_vecs_128(&out[4]);- transpose_vecs_128(&out[8]);- transpose_vecs_128(&out[12]);-}--INLINE void load_counters4(uint64_t counter, bool increment_counter,- __m128i *out_lo, __m128i *out_hi) {- uint64_t mask = (increment_counter ? ~0 : 0);- __m256i mask_vec = _mm256_set1_epi64x(mask);- __m256i deltas = _mm256_setr_epi64x(0, 1, 2, 3);- deltas = _mm256_and_si256(mask_vec, deltas);- __m256i counters =- _mm256_add_epi64(_mm256_set1_epi64x((int64_t)counter), deltas);- *out_lo = _mm256_cvtepi64_epi32(counters);- *out_hi = _mm256_cvtepi64_epi32(_mm256_srli_epi64(counters, 32));-}--static-void blake3_hash4_avx512(const uint8_t *const *inputs, size_t blocks,- const uint32_t key[8], uint64_t counter,- bool increment_counter, uint8_t flags,- uint8_t flags_start, uint8_t flags_end, uint8_t *out) {- __m128i h_vecs[8] = {- set1_128(key[0]), set1_128(key[1]), set1_128(key[2]), set1_128(key[3]),- set1_128(key[4]), set1_128(key[5]), set1_128(key[6]), set1_128(key[7]),- };- __m128i counter_low_vec, counter_high_vec;- load_counters4(counter, increment_counter, &counter_low_vec,- &counter_high_vec);- uint8_t block_flags = flags | flags_start;-- for (size_t block = 0; block < blocks; block++) {- if (block + 1 == blocks) {- block_flags |= flags_end;- }- __m128i block_len_vec = set1_128(BLAKE3_BLOCK_LEN);- __m128i block_flags_vec = set1_128(block_flags);- __m128i msg_vecs[16];- transpose_msg_vecs4(inputs, block * BLAKE3_BLOCK_LEN, msg_vecs);-- __m128i v[16] = {- h_vecs[0], h_vecs[1], h_vecs[2], h_vecs[3],- h_vecs[4], h_vecs[5], h_vecs[6], h_vecs[7],- set1_128(IV[0]), set1_128(IV[1]), set1_128(IV[2]), set1_128(IV[3]),- counter_low_vec, counter_high_vec, block_len_vec, block_flags_vec,- };- round_fn4(v, msg_vecs, 0);- round_fn4(v, msg_vecs, 1);- round_fn4(v, msg_vecs, 2);- round_fn4(v, msg_vecs, 3);- round_fn4(v, msg_vecs, 4);- round_fn4(v, msg_vecs, 5);- round_fn4(v, msg_vecs, 6);- h_vecs[0] = xor_128(v[0], v[8]);- h_vecs[1] = xor_128(v[1], v[9]);- h_vecs[2] = xor_128(v[2], v[10]);- h_vecs[3] = xor_128(v[3], v[11]);- h_vecs[4] = xor_128(v[4], v[12]);- h_vecs[5] = xor_128(v[5], v[13]);- h_vecs[6] = xor_128(v[6], v[14]);- h_vecs[7] = xor_128(v[7], v[15]);-- block_flags = flags;- }-- transpose_vecs_128(&h_vecs[0]);- transpose_vecs_128(&h_vecs[4]);- // The first four vecs now contain the first half of each output, and the- // second four vecs contain the second half of each output.- storeu_128(h_vecs[0], &out[0 * sizeof(__m128i)]);- storeu_128(h_vecs[4], &out[1 * sizeof(__m128i)]);- storeu_128(h_vecs[1], &out[2 * sizeof(__m128i)]);- storeu_128(h_vecs[5], &out[3 * sizeof(__m128i)]);- storeu_128(h_vecs[2], &out[4 * sizeof(__m128i)]);- storeu_128(h_vecs[6], &out[5 * sizeof(__m128i)]);- storeu_128(h_vecs[3], &out[6 * sizeof(__m128i)]);- storeu_128(h_vecs[7], &out[7 * sizeof(__m128i)]);-}--static-void blake3_xof4_avx512(const uint32_t cv[8],- const uint8_t block[BLAKE3_BLOCK_LEN],- uint8_t block_len, uint64_t counter, uint8_t flags,- uint8_t out[4 * 64]) {- __m128i h_vecs[8] = {- set1_128(cv[0]), set1_128(cv[1]), set1_128(cv[2]), set1_128(cv[3]),- set1_128(cv[4]), set1_128(cv[5]), set1_128(cv[6]), set1_128(cv[7]),- };- uint32_t block_words[16];- load_block_words(block, block_words);- __m128i msg_vecs[16];- for (size_t i = 0; i < 16; i++) {- msg_vecs[i] = set1_128(block_words[i]);- }- __m128i counter_low_vec, counter_high_vec;- load_counters4(counter, true, &counter_low_vec, &counter_high_vec);- __m128i block_len_vec = set1_128(block_len);- __m128i block_flags_vec = set1_128(flags);- __m128i v[16] = {- h_vecs[0], h_vecs[1], h_vecs[2], h_vecs[3],- h_vecs[4], h_vecs[5], h_vecs[6], h_vecs[7],- set1_128(IV[0]), set1_128(IV[1]), set1_128(IV[2]), set1_128(IV[3]),- counter_low_vec, counter_high_vec, block_len_vec, block_flags_vec,- };- round_fn4(v, msg_vecs, 0);- round_fn4(v, msg_vecs, 1);- round_fn4(v, msg_vecs, 2);- round_fn4(v, msg_vecs, 3);- round_fn4(v, msg_vecs, 4);- round_fn4(v, msg_vecs, 5);- round_fn4(v, msg_vecs, 6);- for (size_t i = 0; i < 8; i++) {- v[i] = xor_128(v[i], v[i+8]);- v[i+8] = xor_128(v[i+8], h_vecs[i]);- }- transpose_vecs_128(&v[0]);- transpose_vecs_128(&v[4]);- transpose_vecs_128(&v[8]);- transpose_vecs_128(&v[12]);- for (size_t i = 0; i < 4; i++) {- storeu_128(v[i+ 0], &out[(4*i+0) * sizeof(__m128i)]);- storeu_128(v[i+ 4], &out[(4*i+1) * sizeof(__m128i)]);- storeu_128(v[i+ 8], &out[(4*i+2) * sizeof(__m128i)]);- storeu_128(v[i+12], &out[(4*i+3) * sizeof(__m128i)]);- }-}--/*- * ----------------------------------------------------------------------------- * hash8_avx512- * ----------------------------------------------------------------------------- */--INLINE void round_fn8(__m256i v[16], __m256i m[16], size_t r) {- v[0] = add_256(v[0], m[(size_t)MSG_SCHEDULE[r][0]]);- v[1] = add_256(v[1], m[(size_t)MSG_SCHEDULE[r][2]]);- v[2] = add_256(v[2], m[(size_t)MSG_SCHEDULE[r][4]]);- v[3] = add_256(v[3], m[(size_t)MSG_SCHEDULE[r][6]]);- v[0] = add_256(v[0], v[4]);- v[1] = add_256(v[1], v[5]);- v[2] = add_256(v[2], v[6]);- v[3] = add_256(v[3], v[7]);- v[12] = xor_256(v[12], v[0]);- v[13] = xor_256(v[13], v[1]);- v[14] = xor_256(v[14], v[2]);- v[15] = xor_256(v[15], v[3]);- v[12] = rot16_256(v[12]);- v[13] = rot16_256(v[13]);- v[14] = rot16_256(v[14]);- v[15] = rot16_256(v[15]);- v[8] = add_256(v[8], v[12]);- v[9] = add_256(v[9], v[13]);- v[10] = add_256(v[10], v[14]);- v[11] = add_256(v[11], v[15]);- v[4] = xor_256(v[4], v[8]);- v[5] = xor_256(v[5], v[9]);- v[6] = xor_256(v[6], v[10]);- v[7] = xor_256(v[7], v[11]);- v[4] = rot12_256(v[4]);- v[5] = rot12_256(v[5]);- v[6] = rot12_256(v[6]);- v[7] = rot12_256(v[7]);- v[0] = add_256(v[0], m[(size_t)MSG_SCHEDULE[r][1]]);- v[1] = add_256(v[1], m[(size_t)MSG_SCHEDULE[r][3]]);- v[2] = add_256(v[2], m[(size_t)MSG_SCHEDULE[r][5]]);- v[3] = add_256(v[3], m[(size_t)MSG_SCHEDULE[r][7]]);- v[0] = add_256(v[0], v[4]);- v[1] = add_256(v[1], v[5]);- v[2] = add_256(v[2], v[6]);- v[3] = add_256(v[3], v[7]);- v[12] = xor_256(v[12], v[0]);- v[13] = xor_256(v[13], v[1]);- v[14] = xor_256(v[14], v[2]);- v[15] = xor_256(v[15], v[3]);- v[12] = rot8_256(v[12]);- v[13] = rot8_256(v[13]);- v[14] = rot8_256(v[14]);- v[15] = rot8_256(v[15]);- v[8] = add_256(v[8], v[12]);- v[9] = add_256(v[9], v[13]);- v[10] = add_256(v[10], v[14]);- v[11] = add_256(v[11], v[15]);- v[4] = xor_256(v[4], v[8]);- v[5] = xor_256(v[5], v[9]);- v[6] = xor_256(v[6], v[10]);- v[7] = xor_256(v[7], v[11]);- v[4] = rot7_256(v[4]);- v[5] = rot7_256(v[5]);- v[6] = rot7_256(v[6]);- v[7] = rot7_256(v[7]);-- v[0] = add_256(v[0], m[(size_t)MSG_SCHEDULE[r][8]]);- v[1] = add_256(v[1], m[(size_t)MSG_SCHEDULE[r][10]]);- v[2] = add_256(v[2], m[(size_t)MSG_SCHEDULE[r][12]]);- v[3] = add_256(v[3], m[(size_t)MSG_SCHEDULE[r][14]]);- v[0] = add_256(v[0], v[5]);- v[1] = add_256(v[1], v[6]);- v[2] = add_256(v[2], v[7]);- v[3] = add_256(v[3], v[4]);- v[15] = xor_256(v[15], v[0]);- v[12] = xor_256(v[12], v[1]);- v[13] = xor_256(v[13], v[2]);- v[14] = xor_256(v[14], v[3]);- v[15] = rot16_256(v[15]);- v[12] = rot16_256(v[12]);- v[13] = rot16_256(v[13]);- v[14] = rot16_256(v[14]);- v[10] = add_256(v[10], v[15]);- v[11] = add_256(v[11], v[12]);- v[8] = add_256(v[8], v[13]);- v[9] = add_256(v[9], v[14]);- v[5] = xor_256(v[5], v[10]);- v[6] = xor_256(v[6], v[11]);- v[7] = xor_256(v[7], v[8]);- v[4] = xor_256(v[4], v[9]);- v[5] = rot12_256(v[5]);- v[6] = rot12_256(v[6]);- v[7] = rot12_256(v[7]);- v[4] = rot12_256(v[4]);- v[0] = add_256(v[0], m[(size_t)MSG_SCHEDULE[r][9]]);- v[1] = add_256(v[1], m[(size_t)MSG_SCHEDULE[r][11]]);- v[2] = add_256(v[2], m[(size_t)MSG_SCHEDULE[r][13]]);- v[3] = add_256(v[3], m[(size_t)MSG_SCHEDULE[r][15]]);- v[0] = add_256(v[0], v[5]);- v[1] = add_256(v[1], v[6]);- v[2] = add_256(v[2], v[7]);- v[3] = add_256(v[3], v[4]);- v[15] = xor_256(v[15], v[0]);- v[12] = xor_256(v[12], v[1]);- v[13] = xor_256(v[13], v[2]);- v[14] = xor_256(v[14], v[3]);- v[15] = rot8_256(v[15]);- v[12] = rot8_256(v[12]);- v[13] = rot8_256(v[13]);- v[14] = rot8_256(v[14]);- v[10] = add_256(v[10], v[15]);- v[11] = add_256(v[11], v[12]);- v[8] = add_256(v[8], v[13]);- v[9] = add_256(v[9], v[14]);- v[5] = xor_256(v[5], v[10]);- v[6] = xor_256(v[6], v[11]);- v[7] = xor_256(v[7], v[8]);- v[4] = xor_256(v[4], v[9]);- v[5] = rot7_256(v[5]);- v[6] = rot7_256(v[6]);- v[7] = rot7_256(v[7]);- v[4] = rot7_256(v[4]);-}--INLINE void transpose_vecs_256(__m256i vecs[8]) {- // Interleave 32-bit lanes. The low unpack is lanes 00/11/44/55, and the high- // is 22/33/66/77.- __m256i ab_0145 = _mm256_unpacklo_epi32(vecs[0], vecs[1]);- __m256i ab_2367 = _mm256_unpackhi_epi32(vecs[0], vecs[1]);- __m256i cd_0145 = _mm256_unpacklo_epi32(vecs[2], vecs[3]);- __m256i cd_2367 = _mm256_unpackhi_epi32(vecs[2], vecs[3]);- __m256i ef_0145 = _mm256_unpacklo_epi32(vecs[4], vecs[5]);- __m256i ef_2367 = _mm256_unpackhi_epi32(vecs[4], vecs[5]);- __m256i gh_0145 = _mm256_unpacklo_epi32(vecs[6], vecs[7]);- __m256i gh_2367 = _mm256_unpackhi_epi32(vecs[6], vecs[7]);-- // Interleave 64-bit lanes. The low unpack is lanes 00/22 and the high is- // 11/33.- __m256i abcd_04 = _mm256_unpacklo_epi64(ab_0145, cd_0145);- __m256i abcd_15 = _mm256_unpackhi_epi64(ab_0145, cd_0145);- __m256i abcd_26 = _mm256_unpacklo_epi64(ab_2367, cd_2367);- __m256i abcd_37 = _mm256_unpackhi_epi64(ab_2367, cd_2367);- __m256i efgh_04 = _mm256_unpacklo_epi64(ef_0145, gh_0145);- __m256i efgh_15 = _mm256_unpackhi_epi64(ef_0145, gh_0145);- __m256i efgh_26 = _mm256_unpacklo_epi64(ef_2367, gh_2367);- __m256i efgh_37 = _mm256_unpackhi_epi64(ef_2367, gh_2367);-- // Interleave 128-bit lanes.- vecs[0] = _mm256_permute2x128_si256(abcd_04, efgh_04, 0x20);- vecs[1] = _mm256_permute2x128_si256(abcd_15, efgh_15, 0x20);- vecs[2] = _mm256_permute2x128_si256(abcd_26, efgh_26, 0x20);- vecs[3] = _mm256_permute2x128_si256(abcd_37, efgh_37, 0x20);- vecs[4] = _mm256_permute2x128_si256(abcd_04, efgh_04, 0x31);- vecs[5] = _mm256_permute2x128_si256(abcd_15, efgh_15, 0x31);- vecs[6] = _mm256_permute2x128_si256(abcd_26, efgh_26, 0x31);- vecs[7] = _mm256_permute2x128_si256(abcd_37, efgh_37, 0x31);-}--INLINE void transpose_msg_vecs8(const uint8_t *const *inputs,- size_t block_offset, __m256i out[16]) {- out[0] = loadu_256(&inputs[0][block_offset + 0 * sizeof(__m256i)]);- out[1] = loadu_256(&inputs[1][block_offset + 0 * sizeof(__m256i)]);- out[2] = loadu_256(&inputs[2][block_offset + 0 * sizeof(__m256i)]);- out[3] = loadu_256(&inputs[3][block_offset + 0 * sizeof(__m256i)]);- out[4] = loadu_256(&inputs[4][block_offset + 0 * sizeof(__m256i)]);- out[5] = loadu_256(&inputs[5][block_offset + 0 * sizeof(__m256i)]);- out[6] = loadu_256(&inputs[6][block_offset + 0 * sizeof(__m256i)]);- out[7] = loadu_256(&inputs[7][block_offset + 0 * sizeof(__m256i)]);- out[8] = loadu_256(&inputs[0][block_offset + 1 * sizeof(__m256i)]);- out[9] = loadu_256(&inputs[1][block_offset + 1 * sizeof(__m256i)]);- out[10] = loadu_256(&inputs[2][block_offset + 1 * sizeof(__m256i)]);- out[11] = loadu_256(&inputs[3][block_offset + 1 * sizeof(__m256i)]);- out[12] = loadu_256(&inputs[4][block_offset + 1 * sizeof(__m256i)]);- out[13] = loadu_256(&inputs[5][block_offset + 1 * sizeof(__m256i)]);- out[14] = loadu_256(&inputs[6][block_offset + 1 * sizeof(__m256i)]);- out[15] = loadu_256(&inputs[7][block_offset + 1 * sizeof(__m256i)]);- for (size_t i = 0; i < 8; ++i) {- _mm_prefetch((const void *)&inputs[i][block_offset + 256], _MM_HINT_T0);- }- transpose_vecs_256(&out[0]);- transpose_vecs_256(&out[8]);-}--INLINE void load_counters8(uint64_t counter, bool increment_counter,- __m256i *out_lo, __m256i *out_hi) {- uint64_t mask = (increment_counter ? ~0 : 0);- __m512i mask_vec = _mm512_set1_epi64(mask);- __m512i deltas = _mm512_setr_epi64(0, 1, 2, 3, 4, 5, 6, 7);- deltas = _mm512_and_si512(mask_vec, deltas);- __m512i counters =- _mm512_add_epi64(_mm512_set1_epi64((int64_t)counter), deltas);- *out_lo = _mm512_cvtepi64_epi32(counters);- *out_hi = _mm512_cvtepi64_epi32(_mm512_srli_epi64(counters, 32));-}--static-void blake3_hash8_avx512(const uint8_t *const *inputs, size_t blocks,- const uint32_t key[8], uint64_t counter,- bool increment_counter, uint8_t flags,- uint8_t flags_start, uint8_t flags_end, uint8_t *out) {- __m256i h_vecs[8] = {- set1_256(key[0]), set1_256(key[1]), set1_256(key[2]), set1_256(key[3]),- set1_256(key[4]), set1_256(key[5]), set1_256(key[6]), set1_256(key[7]),- };- __m256i counter_low_vec, counter_high_vec;- load_counters8(counter, increment_counter, &counter_low_vec,- &counter_high_vec);- uint8_t block_flags = flags | flags_start;-- for (size_t block = 0; block < blocks; block++) {- if (block + 1 == blocks) {- block_flags |= flags_end;- }- __m256i block_len_vec = set1_256(BLAKE3_BLOCK_LEN);- __m256i block_flags_vec = set1_256(block_flags);- __m256i msg_vecs[16];- transpose_msg_vecs8(inputs, block * BLAKE3_BLOCK_LEN, msg_vecs);-- __m256i v[16] = {- h_vecs[0], h_vecs[1], h_vecs[2], h_vecs[3],- h_vecs[4], h_vecs[5], h_vecs[6], h_vecs[7],- set1_256(IV[0]), set1_256(IV[1]), set1_256(IV[2]), set1_256(IV[3]),- counter_low_vec, counter_high_vec, block_len_vec, block_flags_vec,- };- round_fn8(v, msg_vecs, 0);- round_fn8(v, msg_vecs, 1);- round_fn8(v, msg_vecs, 2);- round_fn8(v, msg_vecs, 3);- round_fn8(v, msg_vecs, 4);- round_fn8(v, msg_vecs, 5);- round_fn8(v, msg_vecs, 6);- h_vecs[0] = xor_256(v[0], v[8]);- h_vecs[1] = xor_256(v[1], v[9]);- h_vecs[2] = xor_256(v[2], v[10]);- h_vecs[3] = xor_256(v[3], v[11]);- h_vecs[4] = xor_256(v[4], v[12]);- h_vecs[5] = xor_256(v[5], v[13]);- h_vecs[6] = xor_256(v[6], v[14]);- h_vecs[7] = xor_256(v[7], v[15]);-- block_flags = flags;- }-- transpose_vecs_256(h_vecs);- storeu_256(h_vecs[0], &out[0 * sizeof(__m256i)]);- storeu_256(h_vecs[1], &out[1 * sizeof(__m256i)]);- storeu_256(h_vecs[2], &out[2 * sizeof(__m256i)]);- storeu_256(h_vecs[3], &out[3 * sizeof(__m256i)]);- storeu_256(h_vecs[4], &out[4 * sizeof(__m256i)]);- storeu_256(h_vecs[5], &out[5 * sizeof(__m256i)]);- storeu_256(h_vecs[6], &out[6 * sizeof(__m256i)]);- storeu_256(h_vecs[7], &out[7 * sizeof(__m256i)]);-}--static-void blake3_xof8_avx512(const uint32_t cv[8],- const uint8_t block[BLAKE3_BLOCK_LEN],- uint8_t block_len, uint64_t counter, uint8_t flags,- uint8_t out[8 * 64]) {- __m256i h_vecs[8] = {- set1_256(cv[0]), set1_256(cv[1]), set1_256(cv[2]), set1_256(cv[3]),- set1_256(cv[4]), set1_256(cv[5]), set1_256(cv[6]), set1_256(cv[7]),- };- uint32_t block_words[16];- load_block_words(block, block_words);- __m256i msg_vecs[16];- for (size_t i = 0; i < 16; i++) {- msg_vecs[i] = set1_256(block_words[i]);- }- __m256i counter_low_vec, counter_high_vec;- load_counters8(counter, true, &counter_low_vec, &counter_high_vec);- __m256i block_len_vec = set1_256(block_len);- __m256i block_flags_vec = set1_256(flags);- __m256i v[16] = {- h_vecs[0], h_vecs[1], h_vecs[2], h_vecs[3],- h_vecs[4], h_vecs[5], h_vecs[6], h_vecs[7],- set1_256(IV[0]), set1_256(IV[1]), set1_256(IV[2]), set1_256(IV[3]),- counter_low_vec, counter_high_vec, block_len_vec, block_flags_vec,- };- round_fn8(v, msg_vecs, 0);- round_fn8(v, msg_vecs, 1);- round_fn8(v, msg_vecs, 2);- round_fn8(v, msg_vecs, 3);- round_fn8(v, msg_vecs, 4);- round_fn8(v, msg_vecs, 5);- round_fn8(v, msg_vecs, 6);- for (size_t i = 0; i < 8; i++) {- v[i] = xor_256(v[i], v[i+8]);- v[i+8] = xor_256(v[i+8], h_vecs[i]);- }- transpose_vecs_256(&v[0]);- transpose_vecs_256(&v[8]);- for (size_t i = 0; i < 8; i++) {- storeu_256(v[i+0], &out[(2*i+0) * sizeof(__m256i)]);- storeu_256(v[i+8], &out[(2*i+1) * sizeof(__m256i)]);- }-}--/*- * ----------------------------------------------------------------------------- * hash16_avx512- * ----------------------------------------------------------------------------- */--INLINE void round_fn16(__m512i v[16], __m512i m[16], size_t r) {- v[0] = add_512(v[0], m[(size_t)MSG_SCHEDULE[r][0]]);- v[1] = add_512(v[1], m[(size_t)MSG_SCHEDULE[r][2]]);- v[2] = add_512(v[2], m[(size_t)MSG_SCHEDULE[r][4]]);- v[3] = add_512(v[3], m[(size_t)MSG_SCHEDULE[r][6]]);- v[0] = add_512(v[0], v[4]);- v[1] = add_512(v[1], v[5]);- v[2] = add_512(v[2], v[6]);- v[3] = add_512(v[3], v[7]);- v[12] = xor_512(v[12], v[0]);- v[13] = xor_512(v[13], v[1]);- v[14] = xor_512(v[14], v[2]);- v[15] = xor_512(v[15], v[3]);- v[12] = rot16_512(v[12]);- v[13] = rot16_512(v[13]);- v[14] = rot16_512(v[14]);- v[15] = rot16_512(v[15]);- v[8] = add_512(v[8], v[12]);- v[9] = add_512(v[9], v[13]);- v[10] = add_512(v[10], v[14]);- v[11] = add_512(v[11], v[15]);- v[4] = xor_512(v[4], v[8]);- v[5] = xor_512(v[5], v[9]);- v[6] = xor_512(v[6], v[10]);- v[7] = xor_512(v[7], v[11]);- v[4] = rot12_512(v[4]);- v[5] = rot12_512(v[5]);- v[6] = rot12_512(v[6]);- v[7] = rot12_512(v[7]);- v[0] = add_512(v[0], m[(size_t)MSG_SCHEDULE[r][1]]);- v[1] = add_512(v[1], m[(size_t)MSG_SCHEDULE[r][3]]);- v[2] = add_512(v[2], m[(size_t)MSG_SCHEDULE[r][5]]);- v[3] = add_512(v[3], m[(size_t)MSG_SCHEDULE[r][7]]);- v[0] = add_512(v[0], v[4]);- v[1] = add_512(v[1], v[5]);- v[2] = add_512(v[2], v[6]);- v[3] = add_512(v[3], v[7]);- v[12] = xor_512(v[12], v[0]);- v[13] = xor_512(v[13], v[1]);- v[14] = xor_512(v[14], v[2]);- v[15] = xor_512(v[15], v[3]);- v[12] = rot8_512(v[12]);- v[13] = rot8_512(v[13]);- v[14] = rot8_512(v[14]);- v[15] = rot8_512(v[15]);- v[8] = add_512(v[8], v[12]);- v[9] = add_512(v[9], v[13]);- v[10] = add_512(v[10], v[14]);- v[11] = add_512(v[11], v[15]);- v[4] = xor_512(v[4], v[8]);- v[5] = xor_512(v[5], v[9]);- v[6] = xor_512(v[6], v[10]);- v[7] = xor_512(v[7], v[11]);- v[4] = rot7_512(v[4]);- v[5] = rot7_512(v[5]);- v[6] = rot7_512(v[6]);- v[7] = rot7_512(v[7]);-- v[0] = add_512(v[0], m[(size_t)MSG_SCHEDULE[r][8]]);- v[1] = add_512(v[1], m[(size_t)MSG_SCHEDULE[r][10]]);- v[2] = add_512(v[2], m[(size_t)MSG_SCHEDULE[r][12]]);- v[3] = add_512(v[3], m[(size_t)MSG_SCHEDULE[r][14]]);- v[0] = add_512(v[0], v[5]);- v[1] = add_512(v[1], v[6]);- v[2] = add_512(v[2], v[7]);- v[3] = add_512(v[3], v[4]);- v[15] = xor_512(v[15], v[0]);- v[12] = xor_512(v[12], v[1]);- v[13] = xor_512(v[13], v[2]);- v[14] = xor_512(v[14], v[3]);- v[15] = rot16_512(v[15]);- v[12] = rot16_512(v[12]);- v[13] = rot16_512(v[13]);- v[14] = rot16_512(v[14]);- v[10] = add_512(v[10], v[15]);- v[11] = add_512(v[11], v[12]);- v[8] = add_512(v[8], v[13]);- v[9] = add_512(v[9], v[14]);- v[5] = xor_512(v[5], v[10]);- v[6] = xor_512(v[6], v[11]);- v[7] = xor_512(v[7], v[8]);- v[4] = xor_512(v[4], v[9]);- v[5] = rot12_512(v[5]);- v[6] = rot12_512(v[6]);- v[7] = rot12_512(v[7]);- v[4] = rot12_512(v[4]);- v[0] = add_512(v[0], m[(size_t)MSG_SCHEDULE[r][9]]);- v[1] = add_512(v[1], m[(size_t)MSG_SCHEDULE[r][11]]);- v[2] = add_512(v[2], m[(size_t)MSG_SCHEDULE[r][13]]);- v[3] = add_512(v[3], m[(size_t)MSG_SCHEDULE[r][15]]);- v[0] = add_512(v[0], v[5]);- v[1] = add_512(v[1], v[6]);- v[2] = add_512(v[2], v[7]);- v[3] = add_512(v[3], v[4]);- v[15] = xor_512(v[15], v[0]);- v[12] = xor_512(v[12], v[1]);- v[13] = xor_512(v[13], v[2]);- v[14] = xor_512(v[14], v[3]);- v[15] = rot8_512(v[15]);- v[12] = rot8_512(v[12]);- v[13] = rot8_512(v[13]);- v[14] = rot8_512(v[14]);- v[10] = add_512(v[10], v[15]);- v[11] = add_512(v[11], v[12]);- v[8] = add_512(v[8], v[13]);- v[9] = add_512(v[9], v[14]);- v[5] = xor_512(v[5], v[10]);- v[6] = xor_512(v[6], v[11]);- v[7] = xor_512(v[7], v[8]);- v[4] = xor_512(v[4], v[9]);- v[5] = rot7_512(v[5]);- v[6] = rot7_512(v[6]);- v[7] = rot7_512(v[7]);- v[4] = rot7_512(v[4]);-}--// 0b10001000, or lanes a0/a2/b0/b2 in little-endian order-#define LO_IMM8 0x88--INLINE __m512i unpack_lo_128(__m512i a, __m512i b) {- return _mm512_shuffle_i32x4(a, b, LO_IMM8);-}--// 0b11011101, or lanes a1/a3/b1/b3 in little-endian order-#define HI_IMM8 0xdd--INLINE __m512i unpack_hi_128(__m512i a, __m512i b) {- return _mm512_shuffle_i32x4(a, b, HI_IMM8);-}--INLINE void transpose_vecs_512(__m512i vecs[16]) {- // Interleave 32-bit lanes. The _0 unpack is lanes- // 0/0/1/1/4/4/5/5/8/8/9/9/12/12/13/13, and the _2 unpack is lanes- // 2/2/3/3/6/6/7/7/10/10/11/11/14/14/15/15.- __m512i ab_0 = _mm512_unpacklo_epi32(vecs[0], vecs[1]);- __m512i ab_2 = _mm512_unpackhi_epi32(vecs[0], vecs[1]);- __m512i cd_0 = _mm512_unpacklo_epi32(vecs[2], vecs[3]);- __m512i cd_2 = _mm512_unpackhi_epi32(vecs[2], vecs[3]);- __m512i ef_0 = _mm512_unpacklo_epi32(vecs[4], vecs[5]);- __m512i ef_2 = _mm512_unpackhi_epi32(vecs[4], vecs[5]);- __m512i gh_0 = _mm512_unpacklo_epi32(vecs[6], vecs[7]);- __m512i gh_2 = _mm512_unpackhi_epi32(vecs[6], vecs[7]);- __m512i ij_0 = _mm512_unpacklo_epi32(vecs[8], vecs[9]);- __m512i ij_2 = _mm512_unpackhi_epi32(vecs[8], vecs[9]);- __m512i kl_0 = _mm512_unpacklo_epi32(vecs[10], vecs[11]);- __m512i kl_2 = _mm512_unpackhi_epi32(vecs[10], vecs[11]);- __m512i mn_0 = _mm512_unpacklo_epi32(vecs[12], vecs[13]);- __m512i mn_2 = _mm512_unpackhi_epi32(vecs[12], vecs[13]);- __m512i op_0 = _mm512_unpacklo_epi32(vecs[14], vecs[15]);- __m512i op_2 = _mm512_unpackhi_epi32(vecs[14], vecs[15]);-- // Interleave 64-bit lanes. The _0 unpack is lanes- // 0/0/0/0/4/4/4/4/8/8/8/8/12/12/12/12, the _1 unpack is lanes- // 1/1/1/1/5/5/5/5/9/9/9/9/13/13/13/13, the _2 unpack is lanes- // 2/2/2/2/6/6/6/6/10/10/10/10/14/14/14/14, and the _3 unpack is lanes- // 3/3/3/3/7/7/7/7/11/11/11/11/15/15/15/15.- __m512i abcd_0 = _mm512_unpacklo_epi64(ab_0, cd_0);- __m512i abcd_1 = _mm512_unpackhi_epi64(ab_0, cd_0);- __m512i abcd_2 = _mm512_unpacklo_epi64(ab_2, cd_2);- __m512i abcd_3 = _mm512_unpackhi_epi64(ab_2, cd_2);- __m512i efgh_0 = _mm512_unpacklo_epi64(ef_0, gh_0);- __m512i efgh_1 = _mm512_unpackhi_epi64(ef_0, gh_0);- __m512i efgh_2 = _mm512_unpacklo_epi64(ef_2, gh_2);- __m512i efgh_3 = _mm512_unpackhi_epi64(ef_2, gh_2);- __m512i ijkl_0 = _mm512_unpacklo_epi64(ij_0, kl_0);- __m512i ijkl_1 = _mm512_unpackhi_epi64(ij_0, kl_0);- __m512i ijkl_2 = _mm512_unpacklo_epi64(ij_2, kl_2);- __m512i ijkl_3 = _mm512_unpackhi_epi64(ij_2, kl_2);- __m512i mnop_0 = _mm512_unpacklo_epi64(mn_0, op_0);- __m512i mnop_1 = _mm512_unpackhi_epi64(mn_0, op_0);- __m512i mnop_2 = _mm512_unpacklo_epi64(mn_2, op_2);- __m512i mnop_3 = _mm512_unpackhi_epi64(mn_2, op_2);-- // Interleave 128-bit lanes. The _0 unpack is- // 0/0/0/0/8/8/8/8/0/0/0/0/8/8/8/8, the _1 unpack is- // 1/1/1/1/9/9/9/9/1/1/1/1/9/9/9/9, and so on.- __m512i abcdefgh_0 = unpack_lo_128(abcd_0, efgh_0);- __m512i abcdefgh_1 = unpack_lo_128(abcd_1, efgh_1);- __m512i abcdefgh_2 = unpack_lo_128(abcd_2, efgh_2);- __m512i abcdefgh_3 = unpack_lo_128(abcd_3, efgh_3);- __m512i abcdefgh_4 = unpack_hi_128(abcd_0, efgh_0);- __m512i abcdefgh_5 = unpack_hi_128(abcd_1, efgh_1);- __m512i abcdefgh_6 = unpack_hi_128(abcd_2, efgh_2);- __m512i abcdefgh_7 = unpack_hi_128(abcd_3, efgh_3);- __m512i ijklmnop_0 = unpack_lo_128(ijkl_0, mnop_0);- __m512i ijklmnop_1 = unpack_lo_128(ijkl_1, mnop_1);- __m512i ijklmnop_2 = unpack_lo_128(ijkl_2, mnop_2);- __m512i ijklmnop_3 = unpack_lo_128(ijkl_3, mnop_3);- __m512i ijklmnop_4 = unpack_hi_128(ijkl_0, mnop_0);- __m512i ijklmnop_5 = unpack_hi_128(ijkl_1, mnop_1);- __m512i ijklmnop_6 = unpack_hi_128(ijkl_2, mnop_2);- __m512i ijklmnop_7 = unpack_hi_128(ijkl_3, mnop_3);-- // Interleave 128-bit lanes again for the final outputs.- vecs[0] = unpack_lo_128(abcdefgh_0, ijklmnop_0);- vecs[1] = unpack_lo_128(abcdefgh_1, ijklmnop_1);- vecs[2] = unpack_lo_128(abcdefgh_2, ijklmnop_2);- vecs[3] = unpack_lo_128(abcdefgh_3, ijklmnop_3);- vecs[4] = unpack_lo_128(abcdefgh_4, ijklmnop_4);- vecs[5] = unpack_lo_128(abcdefgh_5, ijklmnop_5);- vecs[6] = unpack_lo_128(abcdefgh_6, ijklmnop_6);- vecs[7] = unpack_lo_128(abcdefgh_7, ijklmnop_7);- vecs[8] = unpack_hi_128(abcdefgh_0, ijklmnop_0);- vecs[9] = unpack_hi_128(abcdefgh_1, ijklmnop_1);- vecs[10] = unpack_hi_128(abcdefgh_2, ijklmnop_2);- vecs[11] = unpack_hi_128(abcdefgh_3, ijklmnop_3);- vecs[12] = unpack_hi_128(abcdefgh_4, ijklmnop_4);- vecs[13] = unpack_hi_128(abcdefgh_5, ijklmnop_5);- vecs[14] = unpack_hi_128(abcdefgh_6, ijklmnop_6);- vecs[15] = unpack_hi_128(abcdefgh_7, ijklmnop_7);-}--INLINE void transpose_msg_vecs16(const uint8_t *const *inputs,- size_t block_offset, __m512i out[16]) {- out[0] = loadu_512(&inputs[0][block_offset]);- out[1] = loadu_512(&inputs[1][block_offset]);- out[2] = loadu_512(&inputs[2][block_offset]);- out[3] = loadu_512(&inputs[3][block_offset]);- out[4] = loadu_512(&inputs[4][block_offset]);- out[5] = loadu_512(&inputs[5][block_offset]);- out[6] = loadu_512(&inputs[6][block_offset]);- out[7] = loadu_512(&inputs[7][block_offset]);- out[8] = loadu_512(&inputs[8][block_offset]);- out[9] = loadu_512(&inputs[9][block_offset]);- out[10] = loadu_512(&inputs[10][block_offset]);- out[11] = loadu_512(&inputs[11][block_offset]);- out[12] = loadu_512(&inputs[12][block_offset]);- out[13] = loadu_512(&inputs[13][block_offset]);- out[14] = loadu_512(&inputs[14][block_offset]);- out[15] = loadu_512(&inputs[15][block_offset]);- for (size_t i = 0; i < 16; ++i) {- _mm_prefetch((const void *)&inputs[i][block_offset + 256], _MM_HINT_T0);- }- transpose_vecs_512(out);-}--INLINE void load_counters16(uint64_t counter, bool increment_counter,- __m512i *out_lo, __m512i *out_hi) {- const __m512i mask = _mm512_set1_epi32(-(int32_t)increment_counter);- const __m512i deltas = _mm512_set_epi32(15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0);- const __m512i masked_deltas = _mm512_and_si512(deltas, mask);- const __m512i low_words = _mm512_add_epi32(- _mm512_set1_epi32((int32_t)counter),- masked_deltas);- // The carry bit is 1 if the high bit of the word was 1 before addition and is- // 0 after.- // NOTE: It would be a bit more natural to use _mm512_cmp_epu32_mask to- // compute the carry bits here, and originally we did, but that intrinsic is- // broken under GCC 5.4. See https://github.com/BLAKE3-team/BLAKE3/issues/271.- const __m512i carries = _mm512_srli_epi32(- _mm512_andnot_si512(- low_words, // 0 after (gets inverted by andnot)- _mm512_set1_epi32((int32_t)counter)), // and 1 before- 31);- const __m512i high_words = _mm512_add_epi32(- _mm512_set1_epi32((int32_t)(counter >> 32)),- carries);- *out_lo = low_words;- *out_hi = high_words;-}--static-void blake3_hash16_avx512(const uint8_t *const *inputs, size_t blocks,- const uint32_t key[8], uint64_t counter,- bool increment_counter, uint8_t flags,- uint8_t flags_start, uint8_t flags_end,- uint8_t *out) {- __m512i h_vecs[8] = {- set1_512(key[0]), set1_512(key[1]), set1_512(key[2]), set1_512(key[3]),- set1_512(key[4]), set1_512(key[5]), set1_512(key[6]), set1_512(key[7]),- };- __m512i counter_low_vec, counter_high_vec;- load_counters16(counter, increment_counter, &counter_low_vec,- &counter_high_vec);- uint8_t block_flags = flags | flags_start;-- for (size_t block = 0; block < blocks; block++) {- if (block + 1 == blocks) {- block_flags |= flags_end;- }- __m512i block_len_vec = set1_512(BLAKE3_BLOCK_LEN);- __m512i block_flags_vec = set1_512(block_flags);- __m512i msg_vecs[16];- transpose_msg_vecs16(inputs, block * BLAKE3_BLOCK_LEN, msg_vecs);-- __m512i v[16] = {- h_vecs[0], h_vecs[1], h_vecs[2], h_vecs[3],- h_vecs[4], h_vecs[5], h_vecs[6], h_vecs[7],- set1_512(IV[0]), set1_512(IV[1]), set1_512(IV[2]), set1_512(IV[3]),- counter_low_vec, counter_high_vec, block_len_vec, block_flags_vec,- };- round_fn16(v, msg_vecs, 0);- round_fn16(v, msg_vecs, 1);- round_fn16(v, msg_vecs, 2);- round_fn16(v, msg_vecs, 3);- round_fn16(v, msg_vecs, 4);- round_fn16(v, msg_vecs, 5);- round_fn16(v, msg_vecs, 6);- h_vecs[0] = xor_512(v[0], v[8]);- h_vecs[1] = xor_512(v[1], v[9]);- h_vecs[2] = xor_512(v[2], v[10]);- h_vecs[3] = xor_512(v[3], v[11]);- h_vecs[4] = xor_512(v[4], v[12]);- h_vecs[5] = xor_512(v[5], v[13]);- h_vecs[6] = xor_512(v[6], v[14]);- h_vecs[7] = xor_512(v[7], v[15]);-- block_flags = flags;- }-- // transpose_vecs_512 operates on a 16x16 matrix of words, but we only have 8- // state vectors. Pad the matrix with zeros. After transposition, store the- // lower half of each vector.- __m512i padded[16] = {- h_vecs[0], h_vecs[1], h_vecs[2], h_vecs[3],- h_vecs[4], h_vecs[5], h_vecs[6], h_vecs[7],- set1_512(0), set1_512(0), set1_512(0), set1_512(0),- set1_512(0), set1_512(0), set1_512(0), set1_512(0),- };- transpose_vecs_512(padded);- _mm256_mask_storeu_epi32(&out[0 * sizeof(__m256i)], (__mmask8)-1, _mm512_castsi512_si256(padded[0]));- _mm256_mask_storeu_epi32(&out[1 * sizeof(__m256i)], (__mmask8)-1, _mm512_castsi512_si256(padded[1]));- _mm256_mask_storeu_epi32(&out[2 * sizeof(__m256i)], (__mmask8)-1, _mm512_castsi512_si256(padded[2]));- _mm256_mask_storeu_epi32(&out[3 * sizeof(__m256i)], (__mmask8)-1, _mm512_castsi512_si256(padded[3]));- _mm256_mask_storeu_epi32(&out[4 * sizeof(__m256i)], (__mmask8)-1, _mm512_castsi512_si256(padded[4]));- _mm256_mask_storeu_epi32(&out[5 * sizeof(__m256i)], (__mmask8)-1, _mm512_castsi512_si256(padded[5]));- _mm256_mask_storeu_epi32(&out[6 * sizeof(__m256i)], (__mmask8)-1, _mm512_castsi512_si256(padded[6]));- _mm256_mask_storeu_epi32(&out[7 * sizeof(__m256i)], (__mmask8)-1, _mm512_castsi512_si256(padded[7]));- _mm256_mask_storeu_epi32(&out[8 * sizeof(__m256i)], (__mmask8)-1, _mm512_castsi512_si256(padded[8]));- _mm256_mask_storeu_epi32(&out[9 * sizeof(__m256i)], (__mmask8)-1, _mm512_castsi512_si256(padded[9]));- _mm256_mask_storeu_epi32(&out[10 * sizeof(__m256i)], (__mmask8)-1, _mm512_castsi512_si256(padded[10]));- _mm256_mask_storeu_epi32(&out[11 * sizeof(__m256i)], (__mmask8)-1, _mm512_castsi512_si256(padded[11]));- _mm256_mask_storeu_epi32(&out[12 * sizeof(__m256i)], (__mmask8)-1, _mm512_castsi512_si256(padded[12]));- _mm256_mask_storeu_epi32(&out[13 * sizeof(__m256i)], (__mmask8)-1, _mm512_castsi512_si256(padded[13]));- _mm256_mask_storeu_epi32(&out[14 * sizeof(__m256i)], (__mmask8)-1, _mm512_castsi512_si256(padded[14]));- _mm256_mask_storeu_epi32(&out[15 * sizeof(__m256i)], (__mmask8)-1, _mm512_castsi512_si256(padded[15]));-}--static-void blake3_xof16_avx512(const uint32_t cv[8],- const uint8_t block[BLAKE3_BLOCK_LEN],- uint8_t block_len, uint64_t counter, uint8_t flags,- uint8_t out[16 * 64]) {- __m512i h_vecs[8] = {- set1_512(cv[0]), set1_512(cv[1]), set1_512(cv[2]), set1_512(cv[3]),- set1_512(cv[4]), set1_512(cv[5]), set1_512(cv[6]), set1_512(cv[7]),- };- uint32_t block_words[16];- load_block_words(block, block_words);- __m512i msg_vecs[16];- for (size_t i = 0; i < 16; i++) {- msg_vecs[i] = set1_512(block_words[i]);- }- __m512i counter_low_vec, counter_high_vec;- load_counters16(counter, true, &counter_low_vec, &counter_high_vec);- __m512i block_len_vec = set1_512(block_len);- __m512i block_flags_vec = set1_512(flags);- __m512i v[16] = {- h_vecs[0], h_vecs[1], h_vecs[2], h_vecs[3],- h_vecs[4], h_vecs[5], h_vecs[6], h_vecs[7],- set1_512(IV[0]), set1_512(IV[1]), set1_512(IV[2]), set1_512(IV[3]),- counter_low_vec, counter_high_vec, block_len_vec, block_flags_vec,- };- round_fn16(v, msg_vecs, 0);- round_fn16(v, msg_vecs, 1);- round_fn16(v, msg_vecs, 2);- round_fn16(v, msg_vecs, 3);- round_fn16(v, msg_vecs, 4);- round_fn16(v, msg_vecs, 5);- round_fn16(v, msg_vecs, 6);- for (size_t i = 0; i < 8; i++) {- v[i] = xor_512(v[i], v[i+8]);- v[i+8] = xor_512(v[i+8], h_vecs[i]);- }- transpose_vecs_512(&v[0]);- for (size_t i = 0; i < 16; i++) {- storeu_512(v[i], &out[i * sizeof(__m512i)]);- }-}--/*- * ----------------------------------------------------------------------------- * hash_many_avx512- * ----------------------------------------------------------------------------- */--INLINE void hash_one_avx512(const uint8_t *input, size_t blocks,- const uint32_t key[8], uint64_t counter,- uint8_t flags, uint8_t flags_start,- uint8_t flags_end, uint8_t out[BLAKE3_OUT_LEN]) {- uint32_t cv[8];- memcpy(cv, key, BLAKE3_KEY_LEN);- uint8_t block_flags = flags | flags_start;- while (blocks > 0) {- if (blocks == 1) {- block_flags |= flags_end;- }- blake3_compress_in_place_avx512(cv, input, BLAKE3_BLOCK_LEN, counter,- block_flags);- input = &input[BLAKE3_BLOCK_LEN];- blocks -= 1;- block_flags = flags;- }- memcpy(out, cv, BLAKE3_OUT_LEN);-}--void blake3_hash_many_avx512(const uint8_t *const *inputs, size_t num_inputs,- size_t blocks, const uint32_t key[8],- uint64_t counter, bool increment_counter,- uint8_t flags, uint8_t flags_start,- uint8_t flags_end, uint8_t *out) {- while (num_inputs >= 16) {- blake3_hash16_avx512(inputs, blocks, key, counter, increment_counter, flags,- flags_start, flags_end, out);- if (increment_counter) {- counter += 16;- }- inputs += 16;- num_inputs -= 16;- out = &out[16 * BLAKE3_OUT_LEN];- }- while (num_inputs >= 8) {- blake3_hash8_avx512(inputs, blocks, key, counter, increment_counter, flags,- flags_start, flags_end, out);- if (increment_counter) {- counter += 8;- }- inputs += 8;- num_inputs -= 8;- out = &out[8 * BLAKE3_OUT_LEN];- }- while (num_inputs >= 4) {- blake3_hash4_avx512(inputs, blocks, key, counter, increment_counter, flags,- flags_start, flags_end, out);- if (increment_counter) {- counter += 4;- }- inputs += 4;- num_inputs -= 4;- out = &out[4 * BLAKE3_OUT_LEN];- }- while (num_inputs > 0) {- hash_one_avx512(inputs[0], blocks, key, counter, flags, flags_start,- flags_end, out);- if (increment_counter) {- counter += 1;- }- inputs += 1;- num_inputs -= 1;- out = &out[BLAKE3_OUT_LEN];- }-}--void blake3_xof_many_avx512(const uint32_t cv[8],- const uint8_t block[BLAKE3_BLOCK_LEN],- uint8_t block_len, uint64_t counter, uint8_t flags,- uint8_t* out, size_t outblocks) {- while (outblocks >= 16) {- blake3_xof16_avx512(cv, block, block_len, counter, flags, out);- counter += 16;- outblocks -= 16;- out += 16 * BLAKE3_BLOCK_LEN;- }- while (outblocks >= 8) {- blake3_xof8_avx512(cv, block, block_len, counter, flags, out);- counter += 8;- outblocks -= 8;- out += 8 * BLAKE3_BLOCK_LEN;- }- while (outblocks >= 4) {- blake3_xof4_avx512(cv, block, block_len, counter, flags, out);- counter += 4;- outblocks -= 4;- out += 4 * BLAKE3_BLOCK_LEN;- }- while (outblocks > 0) {- blake3_compress_xof_avx512(cv, block, block_len, counter, flags, out);- counter += 1;- outblocks -= 1;- out += BLAKE3_BLOCK_LEN;- }-}--- a/src/src/crypto/blake3/blake3_dispatch.c+++ /dev/null@@ -1,332 +0,0 @@-#include <stdbool.h>-#include <stddef.h>-#include <stdint.h>--#include "blake3_impl.h"--#if defined(_MSC_VER)-#include <Windows.h>-#endif--#if defined(IS_X86)-#if defined(_MSC_VER)-#include <intrin.h>-#elif defined(__GNUC__)-#include <immintrin.h>-#else-#undef IS_X86 /* Unimplemented! */-#endif-#endif--#if !defined(BLAKE3_ATOMICS)-#if defined(__has_include)-#if __has_include(<stdatomic.h>) && !defined(_MSC_VER)-#define BLAKE3_ATOMICS 1-#else-#define BLAKE3_ATOMICS 0-#endif /* __has_include(<stdatomic.h>) && !defined(_MSC_VER) */-#else-#define BLAKE3_ATOMICS 0-#endif /* defined(__has_include) */-#endif /* BLAKE3_ATOMICS */--#if BLAKE3_ATOMICS-#define ATOMIC_INT _Atomic int-#define ATOMIC_LOAD(x) x-#define ATOMIC_STORE(x, y) x = y-#elif defined(_MSC_VER)-#define ATOMIC_INT LONG-#define ATOMIC_LOAD(x) InterlockedOr(&x, 0)-#define ATOMIC_STORE(x, y) InterlockedExchange(&x, y)-#else-#define ATOMIC_INT int-#define ATOMIC_LOAD(x) x-#define ATOMIC_STORE(x, y) x = y-#endif--#define MAYBE_UNUSED(x) (void)((x))--#if defined(IS_X86)-static uint64_t xgetbv(void) {-#if defined(_MSC_VER)- return _xgetbv(0);-#else- uint32_t eax = 0, edx = 0;- __asm__ __volatile__("xgetbv\n" : "=a"(eax), "=d"(edx) : "c"(0));- return ((uint64_t)edx << 32) | eax;-#endif-}--static void cpuid(uint32_t out[4], uint32_t id) {-#if defined(_MSC_VER)- __cpuid((int *)out, id);-#elif defined(__i386__) || defined(_M_IX86)- __asm__ __volatile__("movl %%ebx, %1\n"- "cpuid\n"- "xchgl %1, %%ebx\n"- : "=a"(out[0]), "=r"(out[1]), "=c"(out[2]), "=d"(out[3])- : "a"(id));-#else- __asm__ __volatile__("cpuid\n"- : "=a"(out[0]), "=b"(out[1]), "=c"(out[2]), "=d"(out[3])- : "a"(id));-#endif-}--static void cpuidex(uint32_t out[4], uint32_t id, uint32_t sid) {-#if defined(_MSC_VER)- __cpuidex((int *)out, id, sid);-#elif defined(__i386__) || defined(_M_IX86)- __asm__ __volatile__("movl %%ebx, %1\n"- "cpuid\n"- "xchgl %1, %%ebx\n"- : "=a"(out[0]), "=r"(out[1]), "=c"(out[2]), "=d"(out[3])- : "a"(id), "c"(sid));-#else- __asm__ __volatile__("cpuid\n"- : "=a"(out[0]), "=b"(out[1]), "=c"(out[2]), "=d"(out[3])- : "a"(id), "c"(sid));-#endif-}---enum cpu_feature {- SSE2 = 1 << 0,- SSSE3 = 1 << 1,- SSE41 = 1 << 2,- AVX = 1 << 3,- AVX2 = 1 << 4,- AVX512F = 1 << 5,- AVX512VL = 1 << 6,- /* ... */- UNDEFINED = 1 << 30-};--#if !defined(BLAKE3_TESTING)-static /* Allow the variable to be controlled manually for testing */-#endif- ATOMIC_INT g_cpu_features = UNDEFINED;--#if !defined(BLAKE3_TESTING)-static-#endif- enum cpu_feature- get_cpu_features(void) {-- /* If TSAN detects a data race here, try compiling with -DBLAKE3_ATOMICS=1 */- enum cpu_feature features = ATOMIC_LOAD(g_cpu_features);- if (features != UNDEFINED) {- return features;- } else {-#if defined(IS_X86)- uint32_t regs[4] = {0};- uint32_t *eax = ®s[0], *ebx = ®s[1], *ecx = ®s[2], *edx = ®s[3];- (void)edx;- features = 0;- cpuid(regs, 0);- const int max_id = *eax;- cpuid(regs, 1);-#if defined(__amd64__) || defined(_M_X64)- features |= SSE2;-#else- if (*edx & (1UL << 26))- features |= SSE2;-#endif- if (*ecx & (1UL << 9))- features |= SSSE3;- if (*ecx & (1UL << 19))- features |= SSE41;-- if (*ecx & (1UL << 27)) { // OSXSAVE- const uint64_t mask = xgetbv();- if ((mask & 6) == 6) { // SSE and AVX states- if (*ecx & (1UL << 28))- features |= AVX;- if (max_id >= 7) {- cpuidex(regs, 7, 0);- if (*ebx & (1UL << 5))- features |= AVX2;- if ((mask & 224) == 224) { // Opmask, ZMM_Hi256, Hi16_Zmm- if (*ebx & (1UL << 31))- features |= AVX512VL;- if (*ebx & (1UL << 16))- features |= AVX512F;- }- }- }- }- ATOMIC_STORE(g_cpu_features, features);- return features;-#else- /* How to detect NEON? */- return 0;-#endif- }-}-#endif--void blake3_compress_in_place(uint32_t cv[8],- const uint8_t block[BLAKE3_BLOCK_LEN],- uint8_t block_len, uint64_t counter,- uint8_t flags) {-#if defined(IS_X86)- const enum cpu_feature features = get_cpu_features();- MAYBE_UNUSED(features);-#if !defined(BLAKE3_NO_AVX512)- if (features & AVX512VL) {- blake3_compress_in_place_avx512(cv, block, block_len, counter, flags);- return;- }-#endif-#if !defined(BLAKE3_NO_SSE41)- if (features & SSE41) {- blake3_compress_in_place_sse41(cv, block, block_len, counter, flags);- return;- }-#endif-#if !defined(BLAKE3_NO_SSE2)- if (features & SSE2) {- blake3_compress_in_place_sse2(cv, block, block_len, counter, flags);- return;- }-#endif-#endif- blake3_compress_in_place_portable(cv, block, block_len, counter, flags);-}--void blake3_compress_xof(const uint32_t cv[8],- const uint8_t block[BLAKE3_BLOCK_LEN],- uint8_t block_len, uint64_t counter, uint8_t flags,- uint8_t out[64]) {-#if defined(IS_X86)- const enum cpu_feature features = get_cpu_features();- MAYBE_UNUSED(features);-#if !defined(BLAKE3_NO_AVX512)- if (features & AVX512VL) {- blake3_compress_xof_avx512(cv, block, block_len, counter, flags, out);- return;- }-#endif-#if !defined(BLAKE3_NO_SSE41)- if (features & SSE41) {- blake3_compress_xof_sse41(cv, block, block_len, counter, flags, out);- return;- }-#endif-#if !defined(BLAKE3_NO_SSE2)- if (features & SSE2) {- blake3_compress_xof_sse2(cv, block, block_len, counter, flags, out);- return;- }-#endif-#endif- blake3_compress_xof_portable(cv, block, block_len, counter, flags, out);-}---void blake3_xof_many(const uint32_t cv[8],- const uint8_t block[BLAKE3_BLOCK_LEN],- uint8_t block_len, uint64_t counter, uint8_t flags,- uint8_t out[64], size_t outblocks) {- if (outblocks == 0) {- // The current assembly implementation always outputs at least 1 block.- return;- }-#if defined(IS_X86)- const enum cpu_feature features = get_cpu_features();- MAYBE_UNUSED(features);-#if !defined(_WIN32) && !defined(__CYGWIN__) && !defined(BLAKE3_NO_AVX512)- if (features & AVX512VL) {- blake3_xof_many_avx512(cv, block, block_len, counter, flags, out, outblocks);- return;- }-#endif-#endif- for(size_t i = 0; i < outblocks; ++i) {- blake3_compress_xof(cv, block, block_len, counter + i, flags, out + 64*i);- }-}--void blake3_hash_many(const uint8_t *const *inputs, size_t num_inputs,- size_t blocks, const uint32_t key[8], uint64_t counter,- bool increment_counter, uint8_t flags,- uint8_t flags_start, uint8_t flags_end, uint8_t *out) {-#if defined(IS_X86)- const enum cpu_feature features = get_cpu_features();- MAYBE_UNUSED(features);-#if !defined(BLAKE3_NO_AVX512)- if ((features & (AVX512F|AVX512VL)) == (AVX512F|AVX512VL)) {- blake3_hash_many_avx512(inputs, num_inputs, blocks, key, counter,- increment_counter, flags, flags_start, flags_end,- out);- return;- }-#endif-#if !defined(BLAKE3_NO_AVX2)- if (features & AVX2) {- blake3_hash_many_avx2(inputs, num_inputs, blocks, key, counter,- increment_counter, flags, flags_start, flags_end,- out);- return;- }-#endif-#if !defined(BLAKE3_NO_SSE41)- if (features & SSE41) {- blake3_hash_many_sse41(inputs, num_inputs, blocks, key, counter,- increment_counter, flags, flags_start, flags_end,- out);- return;- }-#endif-#if !defined(BLAKE3_NO_SSE2)- if (features & SSE2) {- blake3_hash_many_sse2(inputs, num_inputs, blocks, key, counter,- increment_counter, flags, flags_start, flags_end,- out);- return;- }-#endif-#endif--#if BLAKE3_USE_NEON == 1- blake3_hash_many_neon(inputs, num_inputs, blocks, key, counter,- increment_counter, flags, flags_start, flags_end, out);- return;-#endif-- blake3_hash_many_portable(inputs, num_inputs, blocks, key, counter,- increment_counter, flags, flags_start, flags_end,- out);-}--// The dynamically detected SIMD degree of the current platform.-size_t blake3_simd_degree(void) {-#if defined(IS_X86)- const enum cpu_feature features = get_cpu_features();- MAYBE_UNUSED(features);-#if !defined(BLAKE3_NO_AVX512)- if ((features & (AVX512F|AVX512VL)) == (AVX512F|AVX512VL)) {- return 16;- }-#endif-#if !defined(BLAKE3_NO_AVX2)- if (features & AVX2) {- return 8;- }-#endif-#if !defined(BLAKE3_NO_SSE41)- if (features & SSE41) {- return 4;- }-#endif-#if !defined(BLAKE3_NO_SSE2)- if (features & SSE2) {- return 4;- }-#endif-#endif-#if BLAKE3_USE_NEON == 1- return 4;-#endif- return 1;-}--- a/src/src/crypto/blake3/blake3_impl.h+++ /dev/null@@ -1,333 +0,0 @@-#ifndef BLAKE3_IMPL_H-#define BLAKE3_IMPL_H--#include <assert.h>-#include <stdbool.h>-#include <stddef.h>-#include <stdint.h>-#include <string.h>--#include "blake3.h"--#ifdef __cplusplus-extern "C" {-#endif--// internal flags-enum blake3_flags {- CHUNK_START = 1 << 0,- CHUNK_END = 1 << 1,- PARENT = 1 << 2,- ROOT = 1 << 3,- KEYED_HASH = 1 << 4,- DERIVE_KEY_CONTEXT = 1 << 5,- DERIVE_KEY_MATERIAL = 1 << 6,-};--// This C implementation tries to support recent versions of GCC, Clang, and-// MSVC.-#if defined(_MSC_VER)-#define INLINE static __forceinline-#else-#define INLINE static inline __attribute__((always_inline))-#endif--#ifdef __cplusplus-#define NOEXCEPT noexcept-#else-#define NOEXCEPT-#endif--#if (defined(__x86_64__) || defined(_M_X64)) && !defined(_M_ARM64EC)-#define IS_X86-#define IS_X86_64-#endif--#if defined(__i386__) || defined(_M_IX86)-#define IS_X86-#define IS_X86_32-#endif--#if defined(__aarch64__) || defined(_M_ARM64) || defined(_M_ARM64EC)-#define IS_AARCH64-#endif--#if defined(IS_X86)-#if defined(_MSC_VER)-#include <intrin.h>-#endif-#endif--#if !defined(BLAKE3_USE_NEON) - // If BLAKE3_USE_NEON not manually set, autodetect based on AArch64ness- #if defined(IS_AARCH64)- #if defined(__ARM_BIG_ENDIAN)- #define BLAKE3_USE_NEON 0- #else- #define BLAKE3_USE_NEON 1- #endif- #else- #define BLAKE3_USE_NEON 0- #endif-#endif--#if defined(IS_X86)-#define MAX_SIMD_DEGREE 16-#elif BLAKE3_USE_NEON == 1-#define MAX_SIMD_DEGREE 4-#else-#define MAX_SIMD_DEGREE 1-#endif--// There are some places where we want a static size that's equal to the-// MAX_SIMD_DEGREE, but also at least 2.-#define MAX_SIMD_DEGREE_OR_2 (MAX_SIMD_DEGREE > 2 ? MAX_SIMD_DEGREE : 2)--static const uint32_t IV[8] = {0x6A09E667UL, 0xBB67AE85UL, 0x3C6EF372UL,- 0xA54FF53AUL, 0x510E527FUL, 0x9B05688CUL,- 0x1F83D9ABUL, 0x5BE0CD19UL};--static const uint8_t MSG_SCHEDULE[7][16] = {- {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},-};--/* Find index of the highest set bit */-/* x is assumed to be nonzero. */-static unsigned int highest_one(uint64_t x) {-#if defined(__GNUC__) || defined(__clang__)- return 63 ^ (unsigned int)__builtin_clzll(x);-#elif defined(_MSC_VER) && defined(IS_X86_64)- unsigned long index;- _BitScanReverse64(&index, x);- return index;-#elif defined(_MSC_VER) && defined(IS_X86_32)- if(x >> 32) {- unsigned long index;- _BitScanReverse(&index, (unsigned long)(x >> 32));- return 32 + index;- } else {- unsigned long index;- _BitScanReverse(&index, (unsigned long)x);- return index;- }-#else- unsigned int c = 0;- if(x & 0xffffffff00000000ULL) { x >>= 32; c += 32; }- if(x & 0x00000000ffff0000ULL) { x >>= 16; c += 16; }- if(x & 0x000000000000ff00ULL) { x >>= 8; c += 8; }- if(x & 0x00000000000000f0ULL) { x >>= 4; c += 4; }- if(x & 0x000000000000000cULL) { x >>= 2; c += 2; }- if(x & 0x0000000000000002ULL) { c += 1; }- return c;-#endif-}--// Count the number of 1 bits.-INLINE unsigned int popcnt(uint64_t x) {-#if defined(__GNUC__) || defined(__clang__)- return (unsigned int)__builtin_popcountll(x);-#else- unsigned int count = 0;- while (x != 0) {- count += 1;- x &= x - 1;- }- return count;-#endif-}--// Largest power of two less than or equal to x. As a special case, returns 1-// when x is 0. -INLINE uint64_t round_down_to_power_of_2(uint64_t x) {- return 1ULL << highest_one(x | 1);-}--INLINE uint32_t counter_low(uint64_t counter) { return (uint32_t)counter; }--INLINE uint32_t counter_high(uint64_t counter) {- return (uint32_t)(counter >> 32);-}--INLINE uint32_t load32(const void *src) {- const uint8_t *p = (const uint8_t *)src;- return ((uint32_t)(p[0]) << 0) | ((uint32_t)(p[1]) << 8) |- ((uint32_t)(p[2]) << 16) | ((uint32_t)(p[3]) << 24);-}--INLINE void load_key_words(const uint8_t key[BLAKE3_KEY_LEN],- uint32_t key_words[8]) {- key_words[0] = load32(&key[0 * 4]);- key_words[1] = load32(&key[1 * 4]);- key_words[2] = load32(&key[2 * 4]);- key_words[3] = load32(&key[3 * 4]);- key_words[4] = load32(&key[4 * 4]);- key_words[5] = load32(&key[5 * 4]);- key_words[6] = load32(&key[6 * 4]);- key_words[7] = load32(&key[7 * 4]);-}--INLINE void load_block_words(const uint8_t block[BLAKE3_BLOCK_LEN],- uint32_t block_words[16]) {- for (size_t i = 0; i < 16; i++) {- block_words[i] = load32(&block[i * 4]);- }-}--INLINE void store32(void *dst, uint32_t w) {- uint8_t *p = (uint8_t *)dst;- p[0] = (uint8_t)(w >> 0);- p[1] = (uint8_t)(w >> 8);- p[2] = (uint8_t)(w >> 16);- p[3] = (uint8_t)(w >> 24);-}--INLINE void store_cv_words(uint8_t bytes_out[32], uint32_t cv_words[8]) {- store32(&bytes_out[0 * 4], cv_words[0]);- store32(&bytes_out[1 * 4], cv_words[1]);- store32(&bytes_out[2 * 4], cv_words[2]);- store32(&bytes_out[3 * 4], cv_words[3]);- store32(&bytes_out[4 * 4], cv_words[4]);- store32(&bytes_out[5 * 4], cv_words[5]);- store32(&bytes_out[6 * 4], cv_words[6]);- store32(&bytes_out[7 * 4], cv_words[7]);-}--void blake3_compress_in_place(uint32_t cv[8],- const uint8_t block[BLAKE3_BLOCK_LEN],- uint8_t block_len, uint64_t counter,- uint8_t flags);--void blake3_compress_xof(const uint32_t cv[8],- const uint8_t block[BLAKE3_BLOCK_LEN],- uint8_t block_len, uint64_t counter, uint8_t flags,- uint8_t out[64]);--void blake3_xof_many(const uint32_t cv[8],- const uint8_t block[BLAKE3_BLOCK_LEN],- uint8_t block_len, uint64_t counter, uint8_t flags,- uint8_t out[64], size_t outblocks);--void blake3_hash_many(const uint8_t *const *inputs, size_t num_inputs,- size_t blocks, const uint32_t key[8], uint64_t counter,- bool increment_counter, uint8_t flags,- uint8_t flags_start, uint8_t flags_end, uint8_t *out);--size_t blake3_simd_degree(void);--BLAKE3_PRIVATE size_t blake3_compress_subtree_wide(const uint8_t *input, size_t input_len,- const uint32_t key[8],- uint64_t chunk_counter, uint8_t flags,- uint8_t *out, bool use_tbb);--#if defined(BLAKE3_USE_TBB)-BLAKE3_PRIVATE void blake3_compress_subtree_wide_join_tbb(- // shared params- const uint32_t key[8], uint8_t flags, bool use_tbb,- // left-hand side params- const uint8_t *l_input, size_t l_input_len, uint64_t l_chunk_counter,- uint8_t *l_cvs, size_t *l_n,- // right-hand side params- const uint8_t *r_input, size_t r_input_len, uint64_t r_chunk_counter,- uint8_t *r_cvs, size_t *r_n) NOEXCEPT;-#endif--// Declarations for implementation-specific functions.-void blake3_compress_in_place_portable(uint32_t cv[8],- const uint8_t block[BLAKE3_BLOCK_LEN],- uint8_t block_len, uint64_t counter,- uint8_t flags);--void blake3_compress_xof_portable(const uint32_t cv[8],- const uint8_t block[BLAKE3_BLOCK_LEN],- uint8_t block_len, uint64_t counter,- uint8_t flags, uint8_t out[64]);--void blake3_hash_many_portable(const uint8_t *const *inputs, size_t num_inputs,- size_t blocks, const uint32_t key[8],- uint64_t counter, bool increment_counter,- uint8_t flags, uint8_t flags_start,- uint8_t flags_end, uint8_t *out);--#if defined(IS_X86)-#if !defined(BLAKE3_NO_SSE2)-void blake3_compress_in_place_sse2(uint32_t cv[8],- const uint8_t block[BLAKE3_BLOCK_LEN],- uint8_t block_len, uint64_t counter,- uint8_t flags);-void blake3_compress_xof_sse2(const uint32_t cv[8],- const uint8_t block[BLAKE3_BLOCK_LEN],- uint8_t block_len, uint64_t counter,- uint8_t flags, uint8_t out[64]);-void blake3_hash_many_sse2(const uint8_t *const *inputs, size_t num_inputs,- size_t blocks, const uint32_t key[8],- uint64_t counter, bool increment_counter,- uint8_t flags, uint8_t flags_start,- uint8_t flags_end, uint8_t *out);-#endif-#if !defined(BLAKE3_NO_SSE41)-void blake3_compress_in_place_sse41(uint32_t cv[8],- const uint8_t block[BLAKE3_BLOCK_LEN],- uint8_t block_len, uint64_t counter,- uint8_t flags);-void blake3_compress_xof_sse41(const uint32_t cv[8],- const uint8_t block[BLAKE3_BLOCK_LEN],- uint8_t block_len, uint64_t counter,- uint8_t flags, uint8_t out[64]);-void blake3_hash_many_sse41(const uint8_t *const *inputs, size_t num_inputs,- size_t blocks, const uint32_t key[8],- uint64_t counter, bool increment_counter,- uint8_t flags, uint8_t flags_start,- uint8_t flags_end, uint8_t *out);-#endif-#if !defined(BLAKE3_NO_AVX2)-void blake3_hash_many_avx2(const uint8_t *const *inputs, size_t num_inputs,- size_t blocks, const uint32_t key[8],- uint64_t counter, bool increment_counter,- uint8_t flags, uint8_t flags_start,- uint8_t flags_end, uint8_t *out);-#endif-#if !defined(BLAKE3_NO_AVX512)-void blake3_compress_in_place_avx512(uint32_t cv[8],- const uint8_t block[BLAKE3_BLOCK_LEN],- uint8_t block_len, uint64_t counter,- uint8_t flags);--void blake3_compress_xof_avx512(const uint32_t cv[8],- const uint8_t block[BLAKE3_BLOCK_LEN],- uint8_t block_len, uint64_t counter,- uint8_t flags, uint8_t out[64]);--void blake3_hash_many_avx512(const uint8_t *const *inputs, size_t num_inputs,- size_t blocks, const uint32_t key[8],- uint64_t counter, bool increment_counter,- uint8_t flags, uint8_t flags_start,- uint8_t flags_end, uint8_t *out);--#if !defined(_WIN32) && !defined(__CYGWIN__)-void blake3_xof_many_avx512(const uint32_t cv[8],- const uint8_t block[BLAKE3_BLOCK_LEN],- uint8_t block_len, uint64_t counter, uint8_t flags,- uint8_t* out, size_t outblocks);-#endif-#endif-#endif--#if BLAKE3_USE_NEON == 1-void blake3_hash_many_neon(const uint8_t *const *inputs, size_t num_inputs,- size_t blocks, const uint32_t key[8],- uint64_t counter, bool increment_counter,- uint8_t flags, uint8_t flags_start,- uint8_t flags_end, uint8_t *out);-#endif--#ifdef __cplusplus-}-#endif--#endif /* BLAKE3_IMPL_H */--- a/src/src/crypto/blake3/blake3_portable.c+++ /dev/null@@ -1,160 +0,0 @@-#include "blake3_impl.h"-#include <string.h>--INLINE uint32_t rotr32(uint32_t w, uint32_t c) {- return (w >> c) | (w << (32 - c));-}--INLINE void g(uint32_t *state, size_t a, size_t b, size_t c, size_t d,- uint32_t x, uint32_t y) {- state[a] = state[a] + state[b] + x;- state[d] = rotr32(state[d] ^ state[a], 16);- state[c] = state[c] + state[d];- state[b] = rotr32(state[b] ^ state[c], 12);- state[a] = state[a] + state[b] + y;- state[d] = rotr32(state[d] ^ state[a], 8);- state[c] = state[c] + state[d];- state[b] = rotr32(state[b] ^ state[c], 7);-}--INLINE void round_fn(uint32_t state[16], const uint32_t *msg, size_t round) {- // Select the message schedule based on the round.- const uint8_t *schedule = MSG_SCHEDULE[round];-- // Mix the columns.- g(state, 0, 4, 8, 12, msg[schedule[0]], msg[schedule[1]]);- g(state, 1, 5, 9, 13, msg[schedule[2]], msg[schedule[3]]);- g(state, 2, 6, 10, 14, msg[schedule[4]], msg[schedule[5]]);- g(state, 3, 7, 11, 15, msg[schedule[6]], msg[schedule[7]]);-- // Mix the rows.- g(state, 0, 5, 10, 15, msg[schedule[8]], msg[schedule[9]]);- g(state, 1, 6, 11, 12, msg[schedule[10]], msg[schedule[11]]);- g(state, 2, 7, 8, 13, msg[schedule[12]], msg[schedule[13]]);- g(state, 3, 4, 9, 14, msg[schedule[14]], msg[schedule[15]]);-}--INLINE void compress_pre(uint32_t state[16], const uint32_t cv[8],- const uint8_t block[BLAKE3_BLOCK_LEN],- uint8_t block_len, uint64_t counter, uint8_t flags) {- uint32_t block_words[16];- block_words[0] = load32(block + 4 * 0);- block_words[1] = load32(block + 4 * 1);- block_words[2] = load32(block + 4 * 2);- block_words[3] = load32(block + 4 * 3);- block_words[4] = load32(block + 4 * 4);- block_words[5] = load32(block + 4 * 5);- block_words[6] = load32(block + 4 * 6);- block_words[7] = load32(block + 4 * 7);- block_words[8] = load32(block + 4 * 8);- block_words[9] = load32(block + 4 * 9);- block_words[10] = load32(block + 4 * 10);- block_words[11] = load32(block + 4 * 11);- block_words[12] = load32(block + 4 * 12);- block_words[13] = load32(block + 4 * 13);- block_words[14] = load32(block + 4 * 14);- block_words[15] = load32(block + 4 * 15);-- state[0] = cv[0];- state[1] = cv[1];- state[2] = cv[2];- state[3] = cv[3];- state[4] = cv[4];- state[5] = cv[5];- state[6] = cv[6];- state[7] = cv[7];- state[8] = IV[0];- state[9] = IV[1];- state[10] = IV[2];- state[11] = IV[3];- state[12] = counter_low(counter);- state[13] = counter_high(counter);- state[14] = (uint32_t)block_len;- state[15] = (uint32_t)flags;-- round_fn(state, &block_words[0], 0);- round_fn(state, &block_words[0], 1);- round_fn(state, &block_words[0], 2);- round_fn(state, &block_words[0], 3);- round_fn(state, &block_words[0], 4);- round_fn(state, &block_words[0], 5);- round_fn(state, &block_words[0], 6);-}--void blake3_compress_in_place_portable(uint32_t cv[8],- const uint8_t block[BLAKE3_BLOCK_LEN],- uint8_t block_len, uint64_t counter,- uint8_t flags) {- uint32_t state[16];- compress_pre(state, cv, block, block_len, counter, flags);- cv[0] = state[0] ^ state[8];- cv[1] = state[1] ^ state[9];- cv[2] = state[2] ^ state[10];- cv[3] = state[3] ^ state[11];- cv[4] = state[4] ^ state[12];- cv[5] = state[5] ^ state[13];- cv[6] = state[6] ^ state[14];- cv[7] = state[7] ^ state[15];-}--void blake3_compress_xof_portable(const uint32_t cv[8],- const uint8_t block[BLAKE3_BLOCK_LEN],- uint8_t block_len, uint64_t counter,- uint8_t flags, uint8_t out[64]) {- uint32_t state[16];- compress_pre(state, cv, block, block_len, counter, flags);-- store32(&out[0 * 4], state[0] ^ state[8]);- store32(&out[1 * 4], state[1] ^ state[9]);- store32(&out[2 * 4], state[2] ^ state[10]);- store32(&out[3 * 4], state[3] ^ state[11]);- store32(&out[4 * 4], state[4] ^ state[12]);- store32(&out[5 * 4], state[5] ^ state[13]);- store32(&out[6 * 4], state[6] ^ state[14]);- store32(&out[7 * 4], state[7] ^ state[15]);- store32(&out[8 * 4], state[8] ^ cv[0]);- store32(&out[9 * 4], state[9] ^ cv[1]);- store32(&out[10 * 4], state[10] ^ cv[2]);- store32(&out[11 * 4], state[11] ^ cv[3]);- store32(&out[12 * 4], state[12] ^ cv[4]);- store32(&out[13 * 4], state[13] ^ cv[5]);- store32(&out[14 * 4], state[14] ^ cv[6]);- store32(&out[15 * 4], state[15] ^ cv[7]);-}--INLINE void hash_one_portable(const uint8_t *input, size_t blocks,- const uint32_t key[8], uint64_t counter,- uint8_t flags, uint8_t flags_start,- uint8_t flags_end, uint8_t out[BLAKE3_OUT_LEN]) {- uint32_t cv[8];- memcpy(cv, key, BLAKE3_KEY_LEN);- uint8_t block_flags = flags | flags_start;- while (blocks > 0) {- if (blocks == 1) {- block_flags |= flags_end;- }- blake3_compress_in_place_portable(cv, input, BLAKE3_BLOCK_LEN, counter,- block_flags);- input = &input[BLAKE3_BLOCK_LEN];- blocks -= 1;- block_flags = flags;- }- store_cv_words(out, cv);-}--void blake3_hash_many_portable(const uint8_t *const *inputs, size_t num_inputs,- size_t blocks, const uint32_t key[8],- uint64_t counter, bool increment_counter,- uint8_t flags, uint8_t flags_start,- uint8_t flags_end, uint8_t *out) {- while (num_inputs > 0) {- hash_one_portable(inputs[0], blocks, key, counter, flags, flags_start,- flags_end, out);- if (increment_counter) {- counter += 1;- }- inputs += 1;- num_inputs -= 1;- out = &out[BLAKE3_OUT_LEN];- }-}--- a/src/src/crypto/blake3/blake3_sse2.c+++ /dev/null@@ -1,566 +0,0 @@-#include "blake3_impl.h"--#include <immintrin.h>--#define DEGREE 4--#define _mm_shuffle_ps2(a, b, c) \- (_mm_castps_si128( \- _mm_shuffle_ps(_mm_castsi128_ps(a), _mm_castsi128_ps(b), (c))))--INLINE __m128i loadu(const uint8_t src[16]) {- return _mm_loadu_si128((const __m128i *)src);-}--INLINE void storeu(__m128i src, uint8_t dest[16]) {- _mm_storeu_si128((__m128i *)dest, src);-}--INLINE __m128i addv(__m128i a, __m128i b) { return _mm_add_epi32(a, b); }--// Note that clang-format doesn't like the name "xor" for some reason.-INLINE __m128i xorv(__m128i a, __m128i b) { return _mm_xor_si128(a, b); }--INLINE __m128i set1(uint32_t x) { return _mm_set1_epi32((int32_t)x); }--INLINE __m128i set4(uint32_t a, uint32_t b, uint32_t c, uint32_t d) {- return _mm_setr_epi32((int32_t)a, (int32_t)b, (int32_t)c, (int32_t)d);-}--INLINE __m128i rot16(__m128i x) {- return _mm_shufflehi_epi16(_mm_shufflelo_epi16(x, 0xB1), 0xB1);-}--INLINE __m128i rot12(__m128i x) {- return xorv(_mm_srli_epi32(x, 12), _mm_slli_epi32(x, 32 - 12));-}--INLINE __m128i rot8(__m128i x) {- return xorv(_mm_srli_epi32(x, 8), _mm_slli_epi32(x, 32 - 8));-}--INLINE __m128i rot7(__m128i x) {- return xorv(_mm_srli_epi32(x, 7), _mm_slli_epi32(x, 32 - 7));-}--INLINE void g1(__m128i *row0, __m128i *row1, __m128i *row2, __m128i *row3,- __m128i m) {- *row0 = addv(addv(*row0, m), *row1);- *row3 = xorv(*row3, *row0);- *row3 = rot16(*row3);- *row2 = addv(*row2, *row3);- *row1 = xorv(*row1, *row2);- *row1 = rot12(*row1);-}--INLINE void g2(__m128i *row0, __m128i *row1, __m128i *row2, __m128i *row3,- __m128i m) {- *row0 = addv(addv(*row0, m), *row1);- *row3 = xorv(*row3, *row0);- *row3 = rot8(*row3);- *row2 = addv(*row2, *row3);- *row1 = xorv(*row1, *row2);- *row1 = rot7(*row1);-}--// Note the optimization here of leaving row1 as the unrotated row, rather than-// row0. All the message loads below are adjusted to compensate for this. See-// discussion at https://github.com/sneves/blake2-avx2/pull/4-INLINE void diagonalize(__m128i *row0, __m128i *row2, __m128i *row3) {- *row0 = _mm_shuffle_epi32(*row0, _MM_SHUFFLE(2, 1, 0, 3));- *row3 = _mm_shuffle_epi32(*row3, _MM_SHUFFLE(1, 0, 3, 2));- *row2 = _mm_shuffle_epi32(*row2, _MM_SHUFFLE(0, 3, 2, 1));-}--INLINE void undiagonalize(__m128i *row0, __m128i *row2, __m128i *row3) {- *row0 = _mm_shuffle_epi32(*row0, _MM_SHUFFLE(0, 3, 2, 1));- *row3 = _mm_shuffle_epi32(*row3, _MM_SHUFFLE(1, 0, 3, 2));- *row2 = _mm_shuffle_epi32(*row2, _MM_SHUFFLE(2, 1, 0, 3));-}--INLINE __m128i blend_epi16(__m128i a, __m128i b, const int16_t imm8) {- const __m128i bits = _mm_set_epi16(0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01);- __m128i mask = _mm_set1_epi16(imm8);- mask = _mm_and_si128(mask, bits);- mask = _mm_cmpeq_epi16(mask, bits);- return _mm_or_si128(_mm_and_si128(mask, b), _mm_andnot_si128(mask, a));-}--INLINE void compress_pre(__m128i rows[4], const uint32_t cv[8],- const uint8_t block[BLAKE3_BLOCK_LEN],- uint8_t block_len, uint64_t counter, uint8_t flags) {- rows[0] = loadu((uint8_t *)&cv[0]);- rows[1] = loadu((uint8_t *)&cv[4]);- rows[2] = set4(IV[0], IV[1], IV[2], IV[3]);- rows[3] = set4(counter_low(counter), counter_high(counter),- (uint32_t)block_len, (uint32_t)flags);-- __m128i m0 = loadu(&block[sizeof(__m128i) * 0]);- __m128i m1 = loadu(&block[sizeof(__m128i) * 1]);- __m128i m2 = loadu(&block[sizeof(__m128i) * 2]);- __m128i m3 = loadu(&block[sizeof(__m128i) * 3]);-- __m128i t0, t1, t2, t3, tt;-- // Round 1. The first round permutes the message words from the original- // input order, into the groups that get mixed in parallel.- t0 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(2, 0, 2, 0)); // 6 4 2 0- g1(&rows[0], &rows[1], &rows[2], &rows[3], t0);- t1 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(3, 1, 3, 1)); // 7 5 3 1- g2(&rows[0], &rows[1], &rows[2], &rows[3], t1);- diagonalize(&rows[0], &rows[2], &rows[3]);- t2 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(2, 0, 2, 0)); // 14 12 10 8- t2 = _mm_shuffle_epi32(t2, _MM_SHUFFLE(2, 1, 0, 3)); // 12 10 8 14- g1(&rows[0], &rows[1], &rows[2], &rows[3], t2);- t3 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(3, 1, 3, 1)); // 15 13 11 9- t3 = _mm_shuffle_epi32(t3, _MM_SHUFFLE(2, 1, 0, 3)); // 13 11 9 15- g2(&rows[0], &rows[1], &rows[2], &rows[3], t3);- undiagonalize(&rows[0], &rows[2], &rows[3]);- m0 = t0;- m1 = t1;- m2 = t2;- m3 = t3;-- // Round 2. This round and all following rounds apply a fixed permutation- // to the message words from the round before.- t0 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(3, 1, 1, 2));- t0 = _mm_shuffle_epi32(t0, _MM_SHUFFLE(0, 3, 2, 1));- g1(&rows[0], &rows[1], &rows[2], &rows[3], t0);- t1 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(3, 3, 2, 2));- tt = _mm_shuffle_epi32(m0, _MM_SHUFFLE(0, 0, 3, 3));- t1 = blend_epi16(tt, t1, 0xCC);- g2(&rows[0], &rows[1], &rows[2], &rows[3], t1);- diagonalize(&rows[0], &rows[2], &rows[3]);- t2 = _mm_unpacklo_epi64(m3, m1);- tt = blend_epi16(t2, m2, 0xC0);- t2 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(1, 3, 2, 0));- g1(&rows[0], &rows[1], &rows[2], &rows[3], t2);- t3 = _mm_unpackhi_epi32(m1, m3);- tt = _mm_unpacklo_epi32(m2, t3);- t3 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(0, 1, 3, 2));- g2(&rows[0], &rows[1], &rows[2], &rows[3], t3);- undiagonalize(&rows[0], &rows[2], &rows[3]);- m0 = t0;- m1 = t1;- m2 = t2;- m3 = t3;-- // Round 3- t0 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(3, 1, 1, 2));- t0 = _mm_shuffle_epi32(t0, _MM_SHUFFLE(0, 3, 2, 1));- g1(&rows[0], &rows[1], &rows[2], &rows[3], t0);- t1 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(3, 3, 2, 2));- tt = _mm_shuffle_epi32(m0, _MM_SHUFFLE(0, 0, 3, 3));- t1 = blend_epi16(tt, t1, 0xCC);- g2(&rows[0], &rows[1], &rows[2], &rows[3], t1);- diagonalize(&rows[0], &rows[2], &rows[3]);- t2 = _mm_unpacklo_epi64(m3, m1);- tt = blend_epi16(t2, m2, 0xC0);- t2 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(1, 3, 2, 0));- g1(&rows[0], &rows[1], &rows[2], &rows[3], t2);- t3 = _mm_unpackhi_epi32(m1, m3);- tt = _mm_unpacklo_epi32(m2, t3);- t3 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(0, 1, 3, 2));- g2(&rows[0], &rows[1], &rows[2], &rows[3], t3);- undiagonalize(&rows[0], &rows[2], &rows[3]);- m0 = t0;- m1 = t1;- m2 = t2;- m3 = t3;-- // Round 4- t0 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(3, 1, 1, 2));- t0 = _mm_shuffle_epi32(t0, _MM_SHUFFLE(0, 3, 2, 1));- g1(&rows[0], &rows[1], &rows[2], &rows[3], t0);- t1 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(3, 3, 2, 2));- tt = _mm_shuffle_epi32(m0, _MM_SHUFFLE(0, 0, 3, 3));- t1 = blend_epi16(tt, t1, 0xCC);- g2(&rows[0], &rows[1], &rows[2], &rows[3], t1);- diagonalize(&rows[0], &rows[2], &rows[3]);- t2 = _mm_unpacklo_epi64(m3, m1);- tt = blend_epi16(t2, m2, 0xC0);- t2 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(1, 3, 2, 0));- g1(&rows[0], &rows[1], &rows[2], &rows[3], t2);- t3 = _mm_unpackhi_epi32(m1, m3);- tt = _mm_unpacklo_epi32(m2, t3);- t3 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(0, 1, 3, 2));- g2(&rows[0], &rows[1], &rows[2], &rows[3], t3);- undiagonalize(&rows[0], &rows[2], &rows[3]);- m0 = t0;- m1 = t1;- m2 = t2;- m3 = t3;-- // Round 5- t0 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(3, 1, 1, 2));- t0 = _mm_shuffle_epi32(t0, _MM_SHUFFLE(0, 3, 2, 1));- g1(&rows[0], &rows[1], &rows[2], &rows[3], t0);- t1 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(3, 3, 2, 2));- tt = _mm_shuffle_epi32(m0, _MM_SHUFFLE(0, 0, 3, 3));- t1 = blend_epi16(tt, t1, 0xCC);- g2(&rows[0], &rows[1], &rows[2], &rows[3], t1);- diagonalize(&rows[0], &rows[2], &rows[3]);- t2 = _mm_unpacklo_epi64(m3, m1);- tt = blend_epi16(t2, m2, 0xC0);- t2 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(1, 3, 2, 0));- g1(&rows[0], &rows[1], &rows[2], &rows[3], t2);- t3 = _mm_unpackhi_epi32(m1, m3);- tt = _mm_unpacklo_epi32(m2, t3);- t3 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(0, 1, 3, 2));- g2(&rows[0], &rows[1], &rows[2], &rows[3], t3);- undiagonalize(&rows[0], &rows[2], &rows[3]);- m0 = t0;- m1 = t1;- m2 = t2;- m3 = t3;-- // Round 6- t0 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(3, 1, 1, 2));- t0 = _mm_shuffle_epi32(t0, _MM_SHUFFLE(0, 3, 2, 1));- g1(&rows[0], &rows[1], &rows[2], &rows[3], t0);- t1 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(3, 3, 2, 2));- tt = _mm_shuffle_epi32(m0, _MM_SHUFFLE(0, 0, 3, 3));- t1 = blend_epi16(tt, t1, 0xCC);- g2(&rows[0], &rows[1], &rows[2], &rows[3], t1);- diagonalize(&rows[0], &rows[2], &rows[3]);- t2 = _mm_unpacklo_epi64(m3, m1);- tt = blend_epi16(t2, m2, 0xC0);- t2 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(1, 3, 2, 0));- g1(&rows[0], &rows[1], &rows[2], &rows[3], t2);- t3 = _mm_unpackhi_epi32(m1, m3);- tt = _mm_unpacklo_epi32(m2, t3);- t3 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(0, 1, 3, 2));- g2(&rows[0], &rows[1], &rows[2], &rows[3], t3);- undiagonalize(&rows[0], &rows[2], &rows[3]);- m0 = t0;- m1 = t1;- m2 = t2;- m3 = t3;-- // Round 7- t0 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(3, 1, 1, 2));- t0 = _mm_shuffle_epi32(t0, _MM_SHUFFLE(0, 3, 2, 1));- g1(&rows[0], &rows[1], &rows[2], &rows[3], t0);- t1 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(3, 3, 2, 2));- tt = _mm_shuffle_epi32(m0, _MM_SHUFFLE(0, 0, 3, 3));- t1 = blend_epi16(tt, t1, 0xCC);- g2(&rows[0], &rows[1], &rows[2], &rows[3], t1);- diagonalize(&rows[0], &rows[2], &rows[3]);- t2 = _mm_unpacklo_epi64(m3, m1);- tt = blend_epi16(t2, m2, 0xC0);- t2 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(1, 3, 2, 0));- g1(&rows[0], &rows[1], &rows[2], &rows[3], t2);- t3 = _mm_unpackhi_epi32(m1, m3);- tt = _mm_unpacklo_epi32(m2, t3);- t3 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(0, 1, 3, 2));- g2(&rows[0], &rows[1], &rows[2], &rows[3], t3);- undiagonalize(&rows[0], &rows[2], &rows[3]);-}--void blake3_compress_in_place_sse2(uint32_t cv[8],- const uint8_t block[BLAKE3_BLOCK_LEN],- uint8_t block_len, uint64_t counter,- uint8_t flags) {- __m128i rows[4];- compress_pre(rows, cv, block, block_len, counter, flags);- storeu(xorv(rows[0], rows[2]), (uint8_t *)&cv[0]);- storeu(xorv(rows[1], rows[3]), (uint8_t *)&cv[4]);-}--void blake3_compress_xof_sse2(const uint32_t cv[8],- const uint8_t block[BLAKE3_BLOCK_LEN],- uint8_t block_len, uint64_t counter,- uint8_t flags, uint8_t out[64]) {- __m128i rows[4];- compress_pre(rows, cv, block, block_len, counter, flags);- storeu(xorv(rows[0], rows[2]), &out[0]);- storeu(xorv(rows[1], rows[3]), &out[16]);- storeu(xorv(rows[2], loadu((uint8_t *)&cv[0])), &out[32]);- storeu(xorv(rows[3], loadu((uint8_t *)&cv[4])), &out[48]);-}--INLINE void round_fn(__m128i v[16], __m128i m[16], size_t r) {- v[0] = addv(v[0], m[(size_t)MSG_SCHEDULE[r][0]]);- v[1] = addv(v[1], m[(size_t)MSG_SCHEDULE[r][2]]);- v[2] = addv(v[2], m[(size_t)MSG_SCHEDULE[r][4]]);- v[3] = addv(v[3], m[(size_t)MSG_SCHEDULE[r][6]]);- v[0] = addv(v[0], v[4]);- v[1] = addv(v[1], v[5]);- v[2] = addv(v[2], v[6]);- v[3] = addv(v[3], v[7]);- v[12] = xorv(v[12], v[0]);- v[13] = xorv(v[13], v[1]);- v[14] = xorv(v[14], v[2]);- v[15] = xorv(v[15], v[3]);- v[12] = rot16(v[12]);- v[13] = rot16(v[13]);- v[14] = rot16(v[14]);- v[15] = rot16(v[15]);- v[8] = addv(v[8], v[12]);- v[9] = addv(v[9], v[13]);- v[10] = addv(v[10], v[14]);- v[11] = addv(v[11], v[15]);- v[4] = xorv(v[4], v[8]);- v[5] = xorv(v[5], v[9]);- v[6] = xorv(v[6], v[10]);- v[7] = xorv(v[7], v[11]);- v[4] = rot12(v[4]);- v[5] = rot12(v[5]);- v[6] = rot12(v[6]);- v[7] = rot12(v[7]);- v[0] = addv(v[0], m[(size_t)MSG_SCHEDULE[r][1]]);- v[1] = addv(v[1], m[(size_t)MSG_SCHEDULE[r][3]]);- v[2] = addv(v[2], m[(size_t)MSG_SCHEDULE[r][5]]);- v[3] = addv(v[3], m[(size_t)MSG_SCHEDULE[r][7]]);- v[0] = addv(v[0], v[4]);- v[1] = addv(v[1], v[5]);- v[2] = addv(v[2], v[6]);- v[3] = addv(v[3], v[7]);- v[12] = xorv(v[12], v[0]);- v[13] = xorv(v[13], v[1]);- v[14] = xorv(v[14], v[2]);- v[15] = xorv(v[15], v[3]);- v[12] = rot8(v[12]);- v[13] = rot8(v[13]);- v[14] = rot8(v[14]);- v[15] = rot8(v[15]);- v[8] = addv(v[8], v[12]);- v[9] = addv(v[9], v[13]);- v[10] = addv(v[10], v[14]);- v[11] = addv(v[11], v[15]);- v[4] = xorv(v[4], v[8]);- v[5] = xorv(v[5], v[9]);- v[6] = xorv(v[6], v[10]);- v[7] = xorv(v[7], v[11]);- v[4] = rot7(v[4]);- v[5] = rot7(v[5]);- v[6] = rot7(v[6]);- v[7] = rot7(v[7]);-- v[0] = addv(v[0], m[(size_t)MSG_SCHEDULE[r][8]]);- v[1] = addv(v[1], m[(size_t)MSG_SCHEDULE[r][10]]);- v[2] = addv(v[2], m[(size_t)MSG_SCHEDULE[r][12]]);- v[3] = addv(v[3], m[(size_t)MSG_SCHEDULE[r][14]]);- v[0] = addv(v[0], v[5]);- v[1] = addv(v[1], v[6]);- v[2] = addv(v[2], v[7]);- v[3] = addv(v[3], v[4]);- v[15] = xorv(v[15], v[0]);- v[12] = xorv(v[12], v[1]);- v[13] = xorv(v[13], v[2]);- v[14] = xorv(v[14], v[3]);- v[15] = rot16(v[15]);- v[12] = rot16(v[12]);- v[13] = rot16(v[13]);- v[14] = rot16(v[14]);- v[10] = addv(v[10], v[15]);- v[11] = addv(v[11], v[12]);- v[8] = addv(v[8], v[13]);- v[9] = addv(v[9], v[14]);- v[5] = xorv(v[5], v[10]);- v[6] = xorv(v[6], v[11]);- v[7] = xorv(v[7], v[8]);- v[4] = xorv(v[4], v[9]);- v[5] = rot12(v[5]);- v[6] = rot12(v[6]);- v[7] = rot12(v[7]);- v[4] = rot12(v[4]);- v[0] = addv(v[0], m[(size_t)MSG_SCHEDULE[r][9]]);- v[1] = addv(v[1], m[(size_t)MSG_SCHEDULE[r][11]]);- v[2] = addv(v[2], m[(size_t)MSG_SCHEDULE[r][13]]);- v[3] = addv(v[3], m[(size_t)MSG_SCHEDULE[r][15]]);- v[0] = addv(v[0], v[5]);- v[1] = addv(v[1], v[6]);- v[2] = addv(v[2], v[7]);- v[3] = addv(v[3], v[4]);- v[15] = xorv(v[15], v[0]);- v[12] = xorv(v[12], v[1]);- v[13] = xorv(v[13], v[2]);- v[14] = xorv(v[14], v[3]);- v[15] = rot8(v[15]);- v[12] = rot8(v[12]);- v[13] = rot8(v[13]);- v[14] = rot8(v[14]);- v[10] = addv(v[10], v[15]);- v[11] = addv(v[11], v[12]);- v[8] = addv(v[8], v[13]);- v[9] = addv(v[9], v[14]);- v[5] = xorv(v[5], v[10]);- v[6] = xorv(v[6], v[11]);- v[7] = xorv(v[7], v[8]);- v[4] = xorv(v[4], v[9]);- v[5] = rot7(v[5]);- v[6] = rot7(v[6]);- v[7] = rot7(v[7]);- v[4] = rot7(v[4]);-}--INLINE void transpose_vecs(__m128i vecs[DEGREE]) {- // Interleave 32-bit lanes. The low unpack is lanes 00/11 and the high is- // 22/33. Note that this doesn't split the vector into two lanes, as the- // AVX2 counterparts do.- __m128i ab_01 = _mm_unpacklo_epi32(vecs[0], vecs[1]);- __m128i ab_23 = _mm_unpackhi_epi32(vecs[0], vecs[1]);- __m128i cd_01 = _mm_unpacklo_epi32(vecs[2], vecs[3]);- __m128i cd_23 = _mm_unpackhi_epi32(vecs[2], vecs[3]);-- // Interleave 64-bit lanes.- __m128i abcd_0 = _mm_unpacklo_epi64(ab_01, cd_01);- __m128i abcd_1 = _mm_unpackhi_epi64(ab_01, cd_01);- __m128i abcd_2 = _mm_unpacklo_epi64(ab_23, cd_23);- __m128i abcd_3 = _mm_unpackhi_epi64(ab_23, cd_23);-- vecs[0] = abcd_0;- vecs[1] = abcd_1;- vecs[2] = abcd_2;- vecs[3] = abcd_3;-}--INLINE void transpose_msg_vecs(const uint8_t *const *inputs,- size_t block_offset, __m128i out[16]) {- out[0] = loadu(&inputs[0][block_offset + 0 * sizeof(__m128i)]);- out[1] = loadu(&inputs[1][block_offset + 0 * sizeof(__m128i)]);- out[2] = loadu(&inputs[2][block_offset + 0 * sizeof(__m128i)]);- out[3] = loadu(&inputs[3][block_offset + 0 * sizeof(__m128i)]);- out[4] = loadu(&inputs[0][block_offset + 1 * sizeof(__m128i)]);- out[5] = loadu(&inputs[1][block_offset + 1 * sizeof(__m128i)]);- out[6] = loadu(&inputs[2][block_offset + 1 * sizeof(__m128i)]);- out[7] = loadu(&inputs[3][block_offset + 1 * sizeof(__m128i)]);- out[8] = loadu(&inputs[0][block_offset + 2 * sizeof(__m128i)]);- out[9] = loadu(&inputs[1][block_offset + 2 * sizeof(__m128i)]);- out[10] = loadu(&inputs[2][block_offset + 2 * sizeof(__m128i)]);- out[11] = loadu(&inputs[3][block_offset + 2 * sizeof(__m128i)]);- out[12] = loadu(&inputs[0][block_offset + 3 * sizeof(__m128i)]);- out[13] = loadu(&inputs[1][block_offset + 3 * sizeof(__m128i)]);- out[14] = loadu(&inputs[2][block_offset + 3 * sizeof(__m128i)]);- out[15] = loadu(&inputs[3][block_offset + 3 * sizeof(__m128i)]);- for (size_t i = 0; i < 4; ++i) {- _mm_prefetch((const void *)&inputs[i][block_offset + 256], _MM_HINT_T0);- }- transpose_vecs(&out[0]);- transpose_vecs(&out[4]);- transpose_vecs(&out[8]);- transpose_vecs(&out[12]);-}--INLINE void load_counters(uint64_t counter, bool increment_counter,- __m128i *out_lo, __m128i *out_hi) {- const __m128i mask = _mm_set1_epi32(-(int32_t)increment_counter);- const __m128i add0 = _mm_set_epi32(3, 2, 1, 0);- const __m128i add1 = _mm_and_si128(mask, add0);- __m128i l = _mm_add_epi32(_mm_set1_epi32((int32_t)counter), add1);- __m128i carry = _mm_cmpgt_epi32(_mm_xor_si128(add1, _mm_set1_epi32(0x80000000)), - _mm_xor_si128( l, _mm_set1_epi32(0x80000000)));- __m128i h = _mm_sub_epi32(_mm_set1_epi32((int32_t)(counter >> 32)), carry);- *out_lo = l;- *out_hi = h;-}--static-void blake3_hash4_sse2(const uint8_t *const *inputs, size_t blocks,- const uint32_t key[8], uint64_t counter,- bool increment_counter, uint8_t flags,- uint8_t flags_start, uint8_t flags_end, uint8_t *out) {- __m128i h_vecs[8] = {- set1(key[0]), set1(key[1]), set1(key[2]), set1(key[3]),- set1(key[4]), set1(key[5]), set1(key[6]), set1(key[7]),- };- __m128i counter_low_vec, counter_high_vec;- load_counters(counter, increment_counter, &counter_low_vec,- &counter_high_vec);- uint8_t block_flags = flags | flags_start;-- for (size_t block = 0; block < blocks; block++) {- if (block + 1 == blocks) {- block_flags |= flags_end;- }- __m128i block_len_vec = set1(BLAKE3_BLOCK_LEN);- __m128i block_flags_vec = set1(block_flags);- __m128i msg_vecs[16];- transpose_msg_vecs(inputs, block * BLAKE3_BLOCK_LEN, msg_vecs);-- __m128i v[16] = {- h_vecs[0], h_vecs[1], h_vecs[2], h_vecs[3],- h_vecs[4], h_vecs[5], h_vecs[6], h_vecs[7],- set1(IV[0]), set1(IV[1]), set1(IV[2]), set1(IV[3]),- counter_low_vec, counter_high_vec, block_len_vec, block_flags_vec,- };- round_fn(v, msg_vecs, 0);- round_fn(v, msg_vecs, 1);- round_fn(v, msg_vecs, 2);- round_fn(v, msg_vecs, 3);- round_fn(v, msg_vecs, 4);- round_fn(v, msg_vecs, 5);- round_fn(v, msg_vecs, 6);- h_vecs[0] = xorv(v[0], v[8]);- h_vecs[1] = xorv(v[1], v[9]);- h_vecs[2] = xorv(v[2], v[10]);- h_vecs[3] = xorv(v[3], v[11]);- h_vecs[4] = xorv(v[4], v[12]);- h_vecs[5] = xorv(v[5], v[13]);- h_vecs[6] = xorv(v[6], v[14]);- h_vecs[7] = xorv(v[7], v[15]);-- block_flags = flags;- }-- transpose_vecs(&h_vecs[0]);- transpose_vecs(&h_vecs[4]);- // The first four vecs now contain the first half of each output, and the- // second four vecs contain the second half of each output.- storeu(h_vecs[0], &out[0 * sizeof(__m128i)]);- storeu(h_vecs[4], &out[1 * sizeof(__m128i)]);- storeu(h_vecs[1], &out[2 * sizeof(__m128i)]);- storeu(h_vecs[5], &out[3 * sizeof(__m128i)]);- storeu(h_vecs[2], &out[4 * sizeof(__m128i)]);- storeu(h_vecs[6], &out[5 * sizeof(__m128i)]);- storeu(h_vecs[3], &out[6 * sizeof(__m128i)]);- storeu(h_vecs[7], &out[7 * sizeof(__m128i)]);-}--INLINE void hash_one_sse2(const uint8_t *input, size_t blocks,- const uint32_t key[8], uint64_t counter,- uint8_t flags, uint8_t flags_start,- uint8_t flags_end, uint8_t out[BLAKE3_OUT_LEN]) {- uint32_t cv[8];- memcpy(cv, key, BLAKE3_KEY_LEN);- uint8_t block_flags = flags | flags_start;- while (blocks > 0) {- if (blocks == 1) {- block_flags |= flags_end;- }- blake3_compress_in_place_sse2(cv, input, BLAKE3_BLOCK_LEN, counter,- block_flags);- input = &input[BLAKE3_BLOCK_LEN];- blocks -= 1;- block_flags = flags;- }- memcpy(out, cv, BLAKE3_OUT_LEN);-}--void blake3_hash_many_sse2(const uint8_t *const *inputs, size_t num_inputs,- size_t blocks, const uint32_t key[8],- uint64_t counter, bool increment_counter,- uint8_t flags, uint8_t flags_start,- uint8_t flags_end, uint8_t *out) {- while (num_inputs >= DEGREE) {- blake3_hash4_sse2(inputs, blocks, key, counter, increment_counter, flags,- flags_start, flags_end, out);- if (increment_counter) {- counter += DEGREE;- }- inputs += DEGREE;- num_inputs -= DEGREE;- out = &out[DEGREE * BLAKE3_OUT_LEN];- }- while (num_inputs > 0) {- hash_one_sse2(inputs[0], blocks, key, counter, flags, flags_start,- flags_end, out);- if (increment_counter) {- counter += 1;- }- inputs += 1;- num_inputs -= 1;- out = &out[BLAKE3_OUT_LEN];- }-}--- a/src/src/crypto/blake3/blake3_sse41.c+++ /dev/null@@ -1,560 +0,0 @@-#include "blake3_impl.h"--#include <immintrin.h>--#define DEGREE 4--#define _mm_shuffle_ps2(a, b, c) \- (_mm_castps_si128( \- _mm_shuffle_ps(_mm_castsi128_ps(a), _mm_castsi128_ps(b), (c))))--INLINE __m128i loadu(const uint8_t src[16]) {- return _mm_loadu_si128((const __m128i *)src);-}--INLINE void storeu(__m128i src, uint8_t dest[16]) {- _mm_storeu_si128((__m128i *)dest, src);-}--INLINE __m128i addv(__m128i a, __m128i b) { return _mm_add_epi32(a, b); }--// Note that clang-format doesn't like the name "xor" for some reason.-INLINE __m128i xorv(__m128i a, __m128i b) { return _mm_xor_si128(a, b); }--INLINE __m128i set1(uint32_t x) { return _mm_set1_epi32((int32_t)x); }--INLINE __m128i set4(uint32_t a, uint32_t b, uint32_t c, uint32_t d) {- return _mm_setr_epi32((int32_t)a, (int32_t)b, (int32_t)c, (int32_t)d);-}--INLINE __m128i rot16(__m128i x) {- return _mm_shuffle_epi8(- x, _mm_set_epi8(13, 12, 15, 14, 9, 8, 11, 10, 5, 4, 7, 6, 1, 0, 3, 2));-}--INLINE __m128i rot12(__m128i x) {- return xorv(_mm_srli_epi32(x, 12), _mm_slli_epi32(x, 32 - 12));-}--INLINE __m128i rot8(__m128i x) {- return _mm_shuffle_epi8(- x, _mm_set_epi8(12, 15, 14, 13, 8, 11, 10, 9, 4, 7, 6, 5, 0, 3, 2, 1));-}--INLINE __m128i rot7(__m128i x) {- return xorv(_mm_srli_epi32(x, 7), _mm_slli_epi32(x, 32 - 7));-}--INLINE void g1(__m128i *row0, __m128i *row1, __m128i *row2, __m128i *row3,- __m128i m) {- *row0 = addv(addv(*row0, m), *row1);- *row3 = xorv(*row3, *row0);- *row3 = rot16(*row3);- *row2 = addv(*row2, *row3);- *row1 = xorv(*row1, *row2);- *row1 = rot12(*row1);-}--INLINE void g2(__m128i *row0, __m128i *row1, __m128i *row2, __m128i *row3,- __m128i m) {- *row0 = addv(addv(*row0, m), *row1);- *row3 = xorv(*row3, *row0);- *row3 = rot8(*row3);- *row2 = addv(*row2, *row3);- *row1 = xorv(*row1, *row2);- *row1 = rot7(*row1);-}--// Note the optimization here of leaving row1 as the unrotated row, rather than-// row0. All the message loads below are adjusted to compensate for this. See-// discussion at https://github.com/sneves/blake2-avx2/pull/4-INLINE void diagonalize(__m128i *row0, __m128i *row2, __m128i *row3) {- *row0 = _mm_shuffle_epi32(*row0, _MM_SHUFFLE(2, 1, 0, 3));- *row3 = _mm_shuffle_epi32(*row3, _MM_SHUFFLE(1, 0, 3, 2));- *row2 = _mm_shuffle_epi32(*row2, _MM_SHUFFLE(0, 3, 2, 1));-}--INLINE void undiagonalize(__m128i *row0, __m128i *row2, __m128i *row3) {- *row0 = _mm_shuffle_epi32(*row0, _MM_SHUFFLE(0, 3, 2, 1));- *row3 = _mm_shuffle_epi32(*row3, _MM_SHUFFLE(1, 0, 3, 2));- *row2 = _mm_shuffle_epi32(*row2, _MM_SHUFFLE(2, 1, 0, 3));-}--INLINE void compress_pre(__m128i rows[4], const uint32_t cv[8],- const uint8_t block[BLAKE3_BLOCK_LEN],- uint8_t block_len, uint64_t counter, uint8_t flags) {- rows[0] = loadu((uint8_t *)&cv[0]);- rows[1] = loadu((uint8_t *)&cv[4]);- rows[2] = set4(IV[0], IV[1], IV[2], IV[3]);- rows[3] = set4(counter_low(counter), counter_high(counter),- (uint32_t)block_len, (uint32_t)flags);-- __m128i m0 = loadu(&block[sizeof(__m128i) * 0]);- __m128i m1 = loadu(&block[sizeof(__m128i) * 1]);- __m128i m2 = loadu(&block[sizeof(__m128i) * 2]);- __m128i m3 = loadu(&block[sizeof(__m128i) * 3]);-- __m128i t0, t1, t2, t3, tt;-- // Round 1. The first round permutes the message words from the original- // input order, into the groups that get mixed in parallel.- t0 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(2, 0, 2, 0)); // 6 4 2 0- g1(&rows[0], &rows[1], &rows[2], &rows[3], t0);- t1 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(3, 1, 3, 1)); // 7 5 3 1- g2(&rows[0], &rows[1], &rows[2], &rows[3], t1);- diagonalize(&rows[0], &rows[2], &rows[3]);- t2 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(2, 0, 2, 0)); // 14 12 10 8- t2 = _mm_shuffle_epi32(t2, _MM_SHUFFLE(2, 1, 0, 3)); // 12 10 8 14- g1(&rows[0], &rows[1], &rows[2], &rows[3], t2);- t3 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(3, 1, 3, 1)); // 15 13 11 9- t3 = _mm_shuffle_epi32(t3, _MM_SHUFFLE(2, 1, 0, 3)); // 13 11 9 15- g2(&rows[0], &rows[1], &rows[2], &rows[3], t3);- undiagonalize(&rows[0], &rows[2], &rows[3]);- m0 = t0;- m1 = t1;- m2 = t2;- m3 = t3;-- // Round 2. This round and all following rounds apply a fixed permutation- // to the message words from the round before.- t0 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(3, 1, 1, 2));- t0 = _mm_shuffle_epi32(t0, _MM_SHUFFLE(0, 3, 2, 1));- g1(&rows[0], &rows[1], &rows[2], &rows[3], t0);- t1 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(3, 3, 2, 2));- tt = _mm_shuffle_epi32(m0, _MM_SHUFFLE(0, 0, 3, 3));- t1 = _mm_blend_epi16(tt, t1, 0xCC);- g2(&rows[0], &rows[1], &rows[2], &rows[3], t1);- diagonalize(&rows[0], &rows[2], &rows[3]);- t2 = _mm_unpacklo_epi64(m3, m1);- tt = _mm_blend_epi16(t2, m2, 0xC0);- t2 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(1, 3, 2, 0));- g1(&rows[0], &rows[1], &rows[2], &rows[3], t2);- t3 = _mm_unpackhi_epi32(m1, m3);- tt = _mm_unpacklo_epi32(m2, t3);- t3 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(0, 1, 3, 2));- g2(&rows[0], &rows[1], &rows[2], &rows[3], t3);- undiagonalize(&rows[0], &rows[2], &rows[3]);- m0 = t0;- m1 = t1;- m2 = t2;- m3 = t3;-- // Round 3- t0 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(3, 1, 1, 2));- t0 = _mm_shuffle_epi32(t0, _MM_SHUFFLE(0, 3, 2, 1));- g1(&rows[0], &rows[1], &rows[2], &rows[3], t0);- t1 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(3, 3, 2, 2));- tt = _mm_shuffle_epi32(m0, _MM_SHUFFLE(0, 0, 3, 3));- t1 = _mm_blend_epi16(tt, t1, 0xCC);- g2(&rows[0], &rows[1], &rows[2], &rows[3], t1);- diagonalize(&rows[0], &rows[2], &rows[3]);- t2 = _mm_unpacklo_epi64(m3, m1);- tt = _mm_blend_epi16(t2, m2, 0xC0);- t2 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(1, 3, 2, 0));- g1(&rows[0], &rows[1], &rows[2], &rows[3], t2);- t3 = _mm_unpackhi_epi32(m1, m3);- tt = _mm_unpacklo_epi32(m2, t3);- t3 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(0, 1, 3, 2));- g2(&rows[0], &rows[1], &rows[2], &rows[3], t3);- undiagonalize(&rows[0], &rows[2], &rows[3]);- m0 = t0;- m1 = t1;- m2 = t2;- m3 = t3;-- // Round 4- t0 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(3, 1, 1, 2));- t0 = _mm_shuffle_epi32(t0, _MM_SHUFFLE(0, 3, 2, 1));- g1(&rows[0], &rows[1], &rows[2], &rows[3], t0);- t1 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(3, 3, 2, 2));- tt = _mm_shuffle_epi32(m0, _MM_SHUFFLE(0, 0, 3, 3));- t1 = _mm_blend_epi16(tt, t1, 0xCC);- g2(&rows[0], &rows[1], &rows[2], &rows[3], t1);- diagonalize(&rows[0], &rows[2], &rows[3]);- t2 = _mm_unpacklo_epi64(m3, m1);- tt = _mm_blend_epi16(t2, m2, 0xC0);- t2 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(1, 3, 2, 0));- g1(&rows[0], &rows[1], &rows[2], &rows[3], t2);- t3 = _mm_unpackhi_epi32(m1, m3);- tt = _mm_unpacklo_epi32(m2, t3);- t3 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(0, 1, 3, 2));- g2(&rows[0], &rows[1], &rows[2], &rows[3], t3);- undiagonalize(&rows[0], &rows[2], &rows[3]);- m0 = t0;- m1 = t1;- m2 = t2;- m3 = t3;-- // Round 5- t0 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(3, 1, 1, 2));- t0 = _mm_shuffle_epi32(t0, _MM_SHUFFLE(0, 3, 2, 1));- g1(&rows[0], &rows[1], &rows[2], &rows[3], t0);- t1 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(3, 3, 2, 2));- tt = _mm_shuffle_epi32(m0, _MM_SHUFFLE(0, 0, 3, 3));- t1 = _mm_blend_epi16(tt, t1, 0xCC);- g2(&rows[0], &rows[1], &rows[2], &rows[3], t1);- diagonalize(&rows[0], &rows[2], &rows[3]);- t2 = _mm_unpacklo_epi64(m3, m1);- tt = _mm_blend_epi16(t2, m2, 0xC0);- t2 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(1, 3, 2, 0));- g1(&rows[0], &rows[1], &rows[2], &rows[3], t2);- t3 = _mm_unpackhi_epi32(m1, m3);- tt = _mm_unpacklo_epi32(m2, t3);- t3 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(0, 1, 3, 2));- g2(&rows[0], &rows[1], &rows[2], &rows[3], t3);- undiagonalize(&rows[0], &rows[2], &rows[3]);- m0 = t0;- m1 = t1;- m2 = t2;- m3 = t3;-- // Round 6- t0 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(3, 1, 1, 2));- t0 = _mm_shuffle_epi32(t0, _MM_SHUFFLE(0, 3, 2, 1));- g1(&rows[0], &rows[1], &rows[2], &rows[3], t0);- t1 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(3, 3, 2, 2));- tt = _mm_shuffle_epi32(m0, _MM_SHUFFLE(0, 0, 3, 3));- t1 = _mm_blend_epi16(tt, t1, 0xCC);- g2(&rows[0], &rows[1], &rows[2], &rows[3], t1);- diagonalize(&rows[0], &rows[2], &rows[3]);- t2 = _mm_unpacklo_epi64(m3, m1);- tt = _mm_blend_epi16(t2, m2, 0xC0);- t2 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(1, 3, 2, 0));- g1(&rows[0], &rows[1], &rows[2], &rows[3], t2);- t3 = _mm_unpackhi_epi32(m1, m3);- tt = _mm_unpacklo_epi32(m2, t3);- t3 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(0, 1, 3, 2));- g2(&rows[0], &rows[1], &rows[2], &rows[3], t3);- undiagonalize(&rows[0], &rows[2], &rows[3]);- m0 = t0;- m1 = t1;- m2 = t2;- m3 = t3;-- // Round 7- t0 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(3, 1, 1, 2));- t0 = _mm_shuffle_epi32(t0, _MM_SHUFFLE(0, 3, 2, 1));- g1(&rows[0], &rows[1], &rows[2], &rows[3], t0);- t1 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(3, 3, 2, 2));- tt = _mm_shuffle_epi32(m0, _MM_SHUFFLE(0, 0, 3, 3));- t1 = _mm_blend_epi16(tt, t1, 0xCC);- g2(&rows[0], &rows[1], &rows[2], &rows[3], t1);- diagonalize(&rows[0], &rows[2], &rows[3]);- t2 = _mm_unpacklo_epi64(m3, m1);- tt = _mm_blend_epi16(t2, m2, 0xC0);- t2 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(1, 3, 2, 0));- g1(&rows[0], &rows[1], &rows[2], &rows[3], t2);- t3 = _mm_unpackhi_epi32(m1, m3);- tt = _mm_unpacklo_epi32(m2, t3);- t3 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(0, 1, 3, 2));- g2(&rows[0], &rows[1], &rows[2], &rows[3], t3);- undiagonalize(&rows[0], &rows[2], &rows[3]);-}--void blake3_compress_in_place_sse41(uint32_t cv[8],- const uint8_t block[BLAKE3_BLOCK_LEN],- uint8_t block_len, uint64_t counter,- uint8_t flags) {- __m128i rows[4];- compress_pre(rows, cv, block, block_len, counter, flags);- storeu(xorv(rows[0], rows[2]), (uint8_t *)&cv[0]);- storeu(xorv(rows[1], rows[3]), (uint8_t *)&cv[4]);-}--void blake3_compress_xof_sse41(const uint32_t cv[8],- const uint8_t block[BLAKE3_BLOCK_LEN],- uint8_t block_len, uint64_t counter,- uint8_t flags, uint8_t out[64]) {- __m128i rows[4];- compress_pre(rows, cv, block, block_len, counter, flags);- storeu(xorv(rows[0], rows[2]), &out[0]);- storeu(xorv(rows[1], rows[3]), &out[16]);- storeu(xorv(rows[2], loadu((uint8_t *)&cv[0])), &out[32]);- storeu(xorv(rows[3], loadu((uint8_t *)&cv[4])), &out[48]);-}--INLINE void round_fn(__m128i v[16], __m128i m[16], size_t r) {- v[0] = addv(v[0], m[(size_t)MSG_SCHEDULE[r][0]]);- v[1] = addv(v[1], m[(size_t)MSG_SCHEDULE[r][2]]);- v[2] = addv(v[2], m[(size_t)MSG_SCHEDULE[r][4]]);- v[3] = addv(v[3], m[(size_t)MSG_SCHEDULE[r][6]]);- v[0] = addv(v[0], v[4]);- v[1] = addv(v[1], v[5]);- v[2] = addv(v[2], v[6]);- v[3] = addv(v[3], v[7]);- v[12] = xorv(v[12], v[0]);- v[13] = xorv(v[13], v[1]);- v[14] = xorv(v[14], v[2]);- v[15] = xorv(v[15], v[3]);- v[12] = rot16(v[12]);- v[13] = rot16(v[13]);- v[14] = rot16(v[14]);- v[15] = rot16(v[15]);- v[8] = addv(v[8], v[12]);- v[9] = addv(v[9], v[13]);- v[10] = addv(v[10], v[14]);- v[11] = addv(v[11], v[15]);- v[4] = xorv(v[4], v[8]);- v[5] = xorv(v[5], v[9]);- v[6] = xorv(v[6], v[10]);- v[7] = xorv(v[7], v[11]);- v[4] = rot12(v[4]);- v[5] = rot12(v[5]);- v[6] = rot12(v[6]);- v[7] = rot12(v[7]);- v[0] = addv(v[0], m[(size_t)MSG_SCHEDULE[r][1]]);- v[1] = addv(v[1], m[(size_t)MSG_SCHEDULE[r][3]]);- v[2] = addv(v[2], m[(size_t)MSG_SCHEDULE[r][5]]);- v[3] = addv(v[3], m[(size_t)MSG_SCHEDULE[r][7]]);- v[0] = addv(v[0], v[4]);- v[1] = addv(v[1], v[5]);- v[2] = addv(v[2], v[6]);- v[3] = addv(v[3], v[7]);- v[12] = xorv(v[12], v[0]);- v[13] = xorv(v[13], v[1]);- v[14] = xorv(v[14], v[2]);- v[15] = xorv(v[15], v[3]);- v[12] = rot8(v[12]);- v[13] = rot8(v[13]);- v[14] = rot8(v[14]);- v[15] = rot8(v[15]);- v[8] = addv(v[8], v[12]);- v[9] = addv(v[9], v[13]);- v[10] = addv(v[10], v[14]);- v[11] = addv(v[11], v[15]);- v[4] = xorv(v[4], v[8]);- v[5] = xorv(v[5], v[9]);- v[6] = xorv(v[6], v[10]);- v[7] = xorv(v[7], v[11]);- v[4] = rot7(v[4]);- v[5] = rot7(v[5]);- v[6] = rot7(v[6]);- v[7] = rot7(v[7]);-- v[0] = addv(v[0], m[(size_t)MSG_SCHEDULE[r][8]]);- v[1] = addv(v[1], m[(size_t)MSG_SCHEDULE[r][10]]);- v[2] = addv(v[2], m[(size_t)MSG_SCHEDULE[r][12]]);- v[3] = addv(v[3], m[(size_t)MSG_SCHEDULE[r][14]]);- v[0] = addv(v[0], v[5]);- v[1] = addv(v[1], v[6]);- v[2] = addv(v[2], v[7]);- v[3] = addv(v[3], v[4]);- v[15] = xorv(v[15], v[0]);- v[12] = xorv(v[12], v[1]);- v[13] = xorv(v[13], v[2]);- v[14] = xorv(v[14], v[3]);- v[15] = rot16(v[15]);- v[12] = rot16(v[12]);- v[13] = rot16(v[13]);- v[14] = rot16(v[14]);- v[10] = addv(v[10], v[15]);- v[11] = addv(v[11], v[12]);- v[8] = addv(v[8], v[13]);- v[9] = addv(v[9], v[14]);- v[5] = xorv(v[5], v[10]);- v[6] = xorv(v[6], v[11]);- v[7] = xorv(v[7], v[8]);- v[4] = xorv(v[4], v[9]);- v[5] = rot12(v[5]);- v[6] = rot12(v[6]);- v[7] = rot12(v[7]);- v[4] = rot12(v[4]);- v[0] = addv(v[0], m[(size_t)MSG_SCHEDULE[r][9]]);- v[1] = addv(v[1], m[(size_t)MSG_SCHEDULE[r][11]]);- v[2] = addv(v[2], m[(size_t)MSG_SCHEDULE[r][13]]);- v[3] = addv(v[3], m[(size_t)MSG_SCHEDULE[r][15]]);- v[0] = addv(v[0], v[5]);- v[1] = addv(v[1], v[6]);- v[2] = addv(v[2], v[7]);- v[3] = addv(v[3], v[4]);- v[15] = xorv(v[15], v[0]);- v[12] = xorv(v[12], v[1]);- v[13] = xorv(v[13], v[2]);- v[14] = xorv(v[14], v[3]);- v[15] = rot8(v[15]);- v[12] = rot8(v[12]);- v[13] = rot8(v[13]);- v[14] = rot8(v[14]);- v[10] = addv(v[10], v[15]);- v[11] = addv(v[11], v[12]);- v[8] = addv(v[8], v[13]);- v[9] = addv(v[9], v[14]);- v[5] = xorv(v[5], v[10]);- v[6] = xorv(v[6], v[11]);- v[7] = xorv(v[7], v[8]);- v[4] = xorv(v[4], v[9]);- v[5] = rot7(v[5]);- v[6] = rot7(v[6]);- v[7] = rot7(v[7]);- v[4] = rot7(v[4]);-}--INLINE void transpose_vecs(__m128i vecs[DEGREE]) {- // Interleave 32-bit lanes. The low unpack is lanes 00/11 and the high is- // 22/33. Note that this doesn't split the vector into two lanes, as the- // AVX2 counterparts do.- __m128i ab_01 = _mm_unpacklo_epi32(vecs[0], vecs[1]);- __m128i ab_23 = _mm_unpackhi_epi32(vecs[0], vecs[1]);- __m128i cd_01 = _mm_unpacklo_epi32(vecs[2], vecs[3]);- __m128i cd_23 = _mm_unpackhi_epi32(vecs[2], vecs[3]);-- // Interleave 64-bit lanes.- __m128i abcd_0 = _mm_unpacklo_epi64(ab_01, cd_01);- __m128i abcd_1 = _mm_unpackhi_epi64(ab_01, cd_01);- __m128i abcd_2 = _mm_unpacklo_epi64(ab_23, cd_23);- __m128i abcd_3 = _mm_unpackhi_epi64(ab_23, cd_23);-- vecs[0] = abcd_0;- vecs[1] = abcd_1;- vecs[2] = abcd_2;- vecs[3] = abcd_3;-}--INLINE void transpose_msg_vecs(const uint8_t *const *inputs,- size_t block_offset, __m128i out[16]) {- out[0] = loadu(&inputs[0][block_offset + 0 * sizeof(__m128i)]);- out[1] = loadu(&inputs[1][block_offset + 0 * sizeof(__m128i)]);- out[2] = loadu(&inputs[2][block_offset + 0 * sizeof(__m128i)]);- out[3] = loadu(&inputs[3][block_offset + 0 * sizeof(__m128i)]);- out[4] = loadu(&inputs[0][block_offset + 1 * sizeof(__m128i)]);- out[5] = loadu(&inputs[1][block_offset + 1 * sizeof(__m128i)]);- out[6] = loadu(&inputs[2][block_offset + 1 * sizeof(__m128i)]);- out[7] = loadu(&inputs[3][block_offset + 1 * sizeof(__m128i)]);- out[8] = loadu(&inputs[0][block_offset + 2 * sizeof(__m128i)]);- out[9] = loadu(&inputs[1][block_offset + 2 * sizeof(__m128i)]);- out[10] = loadu(&inputs[2][block_offset + 2 * sizeof(__m128i)]);- out[11] = loadu(&inputs[3][block_offset + 2 * sizeof(__m128i)]);- out[12] = loadu(&inputs[0][block_offset + 3 * sizeof(__m128i)]);- out[13] = loadu(&inputs[1][block_offset + 3 * sizeof(__m128i)]);- out[14] = loadu(&inputs[2][block_offset + 3 * sizeof(__m128i)]);- out[15] = loadu(&inputs[3][block_offset + 3 * sizeof(__m128i)]);- for (size_t i = 0; i < 4; ++i) {- _mm_prefetch((const void *)&inputs[i][block_offset + 256], _MM_HINT_T0);- }- transpose_vecs(&out[0]);- transpose_vecs(&out[4]);- transpose_vecs(&out[8]);- transpose_vecs(&out[12]);-}--INLINE void load_counters(uint64_t counter, bool increment_counter,- __m128i *out_lo, __m128i *out_hi) {- const __m128i mask = _mm_set1_epi32(-(int32_t)increment_counter);- const __m128i add0 = _mm_set_epi32(3, 2, 1, 0);- const __m128i add1 = _mm_and_si128(mask, add0);- __m128i l = _mm_add_epi32(_mm_set1_epi32((int32_t)counter), add1);- __m128i carry = _mm_cmpgt_epi32(_mm_xor_si128(add1, _mm_set1_epi32(0x80000000)), - _mm_xor_si128( l, _mm_set1_epi32(0x80000000)));- __m128i h = _mm_sub_epi32(_mm_set1_epi32((int32_t)(counter >> 32)), carry);- *out_lo = l;- *out_hi = h;-}--static-void blake3_hash4_sse41(const uint8_t *const *inputs, size_t blocks,- const uint32_t key[8], uint64_t counter,- bool increment_counter, uint8_t flags,- uint8_t flags_start, uint8_t flags_end, uint8_t *out) {- __m128i h_vecs[8] = {- set1(key[0]), set1(key[1]), set1(key[2]), set1(key[3]),- set1(key[4]), set1(key[5]), set1(key[6]), set1(key[7]),- };- __m128i counter_low_vec, counter_high_vec;- load_counters(counter, increment_counter, &counter_low_vec,- &counter_high_vec);- uint8_t block_flags = flags | flags_start;-- for (size_t block = 0; block < blocks; block++) {- if (block + 1 == blocks) {- block_flags |= flags_end;- }- __m128i block_len_vec = set1(BLAKE3_BLOCK_LEN);- __m128i block_flags_vec = set1(block_flags);- __m128i msg_vecs[16];- transpose_msg_vecs(inputs, block * BLAKE3_BLOCK_LEN, msg_vecs);-- __m128i v[16] = {- h_vecs[0], h_vecs[1], h_vecs[2], h_vecs[3],- h_vecs[4], h_vecs[5], h_vecs[6], h_vecs[7],- set1(IV[0]), set1(IV[1]), set1(IV[2]), set1(IV[3]),- counter_low_vec, counter_high_vec, block_len_vec, block_flags_vec,- };- round_fn(v, msg_vecs, 0);- round_fn(v, msg_vecs, 1);- round_fn(v, msg_vecs, 2);- round_fn(v, msg_vecs, 3);- round_fn(v, msg_vecs, 4);- round_fn(v, msg_vecs, 5);- round_fn(v, msg_vecs, 6);- h_vecs[0] = xorv(v[0], v[8]);- h_vecs[1] = xorv(v[1], v[9]);- h_vecs[2] = xorv(v[2], v[10]);- h_vecs[3] = xorv(v[3], v[11]);- h_vecs[4] = xorv(v[4], v[12]);- h_vecs[5] = xorv(v[5], v[13]);- h_vecs[6] = xorv(v[6], v[14]);- h_vecs[7] = xorv(v[7], v[15]);-- block_flags = flags;- }-- transpose_vecs(&h_vecs[0]);- transpose_vecs(&h_vecs[4]);- // The first four vecs now contain the first half of each output, and the- // second four vecs contain the second half of each output.- storeu(h_vecs[0], &out[0 * sizeof(__m128i)]);- storeu(h_vecs[4], &out[1 * sizeof(__m128i)]);- storeu(h_vecs[1], &out[2 * sizeof(__m128i)]);- storeu(h_vecs[5], &out[3 * sizeof(__m128i)]);- storeu(h_vecs[2], &out[4 * sizeof(__m128i)]);- storeu(h_vecs[6], &out[5 * sizeof(__m128i)]);- storeu(h_vecs[3], &out[6 * sizeof(__m128i)]);- storeu(h_vecs[7], &out[7 * sizeof(__m128i)]);-}--INLINE void hash_one_sse41(const uint8_t *input, size_t blocks,- const uint32_t key[8], uint64_t counter,- uint8_t flags, uint8_t flags_start,- uint8_t flags_end, uint8_t out[BLAKE3_OUT_LEN]) {- uint32_t cv[8];- memcpy(cv, key, BLAKE3_KEY_LEN);- uint8_t block_flags = flags | flags_start;- while (blocks > 0) {- if (blocks == 1) {- block_flags |= flags_end;- }- blake3_compress_in_place_sse41(cv, input, BLAKE3_BLOCK_LEN, counter,- block_flags);- input = &input[BLAKE3_BLOCK_LEN];- blocks -= 1;- block_flags = flags;- }- memcpy(out, cv, BLAKE3_OUT_LEN);-}--void blake3_hash_many_sse41(const uint8_t *const *inputs, size_t num_inputs,- size_t blocks, const uint32_t key[8],- uint64_t counter, bool increment_counter,- uint8_t flags, uint8_t flags_start,- uint8_t flags_end, uint8_t *out) {- while (num_inputs >= DEGREE) {- blake3_hash4_sse41(inputs, blocks, key, counter, increment_counter, flags,- flags_start, flags_end, out);- if (increment_counter) {- counter += DEGREE;- }- inputs += DEGREE;- num_inputs -= DEGREE;- out = &out[DEGREE * BLAKE3_OUT_LEN];- }- while (num_inputs > 0) {- hash_one_sse41(inputs[0], blocks, key, counter, flags, flags_start,- flags_end, out);- if (increment_counter) {- counter += 1;- }- inputs += 1;- num_inputs -= 1;- out = &out[BLAKE3_OUT_LEN];- }-}--- a/src/src/crypto/blake3_c.c+++ /dev/null@@ -1,29 +0,0 @@-/* Thin adapter from the veins runtime to the vendored BLAKE3 C library. */--#include "blake3/blake3.h"--#include <stddef.h>-#include <stdint.h>--void veins_blake3(const uint8_t *data, size_t len, uint8_t out[32]) {- blake3_hasher hasher;- blake3_hasher_init(&hasher);- blake3_hasher_update(&hasher, data, len);- blake3_hasher_finalize(&hasher, out, 32);-}--size_t veins_blake3_state_size(void) {- return sizeof(blake3_hasher);-}--void veins_blake3_init(void *state) {- blake3_hasher_init((blake3_hasher *)state);-}--void veins_blake3_update(void *state, const uint8_t *data, size_t len) {- blake3_hasher_update((blake3_hasher *)state, data, len);-}--void veins_blake3_final(void *state, uint8_t out[32]) {- blake3_hasher_finalize((const blake3_hasher *)state, out, 32);-}--- a/src/src/git/export.sx+++ /dev/null@@ -1,1082 +0,0 @@-/// Export veins commits into the bare git mirror.-///-/// Objects are written as loose git objects so export is incremental: only-/// commits missing from the ID map are visited, and each object is hashed-/// exactly once.--lib "z"--val str = use("std/string")-val stdio = use("std/stdio")-val msg = use("../core/msg.sx")-val bytes = use("../core/bytes.sx")-val buf = use("../core/buf.sx")-val lists = use("../core/lists.sx")-val prim = use("../core/primitives.sx")-val objid = use("../object/id.sx")-val tree = use("../object/tree.sx")-val commit = use("../object/commit.sx")-val view = use("../object/view.sx")-val graph = use("../object/graph.sx")-val treewalk = use("../object/treewalk.sx")-val content = use("../object/content.sx")-val store = use("../store/store.sx")-val state = use("../store/state.sx")-val layout = use("../store/layout.sx")-val files = use("../io/files.sx")-val nativeio = use("../io/native.sx")-val object = use("object.sx")-val format = use("format.sx")-val oidmap = use("oidmap.sx")-val gitmap = use("map.sx")-val lazy = use("lazy.sx")--extern (C) fn compress2(- dest: ref u8,- dest_len: ref u64,- source: ref u8,- source_len: u64,- level: i32-) i32 = "compress2"-extern (C) fn compressBound(source_len: u64) u64 = "compressBound"--type ExportCtx = {- repo: mut layout.Repo- handles: list[ref store.Handle]- commits: mut oidmap.OidMap- trees: mut oidmap.OidMap- blobs: mut oidmap.OidMap- native: mut list[objid.Id]- git: mut object.GitRepo- git_open: mut bool- failed: mut bool-}--type Mark = {- id: mut objid.Id- expanded: mut bool-}--fn copy_id(id: objid.Id) objid.Id = trust {- val out: ref u8 = @alloc(32) as ref u8- @memcpy(out as ref void, id.ptr as ref void, 32)- return objid.id(out)-}--fn contains(ids: list[objid.Id], id: objid.Id) bool = trust {- for x in ids {- if objid.Id.eql(x, id) {- return true- }- }- return false-}--fn free_ids(ids: list[objid.Id]) void = trust {- for id in ids {- if id.ptr != none {- val p: mut ref void = id.ptr as ref void- @free(p)- }- }- @listfree(ids)-}--fn reverse_lookup(map: oidmap.OidMap, id: objid.Id) option[bytes.Bytes] = trust {- val i: mut usize = 0- for i < map.cap {- if oidmap.slot_used(map, i) {- val value: bytes.Bytes = oidmap.slot_value(map, i)- val same: bool = bytes.Bytes.eql(- bytes.Bytes.slice(value, 0, 32),- bytes.bytes(id.ptr, 32)- )- if same {- return some(bytes.Bytes.dup(oidmap.slot_oid(map, i)))- }- }- i++- }- return none-}--fn map_put(map: mut oidmap.OidMap, git_oid: bytes.Bytes, id: objid.Id) void = trust {- oidmap.put(map, git_oid, bytes.bytes(id.ptr, 32))-}--fn hex_oid(oid: bytes.Bytes) ref u8 = trust {- val out: ref u8 = @alloc(41) as ref u8- objid.hex_encode(oid.ptr, 20, out)- @store8(@ptradd(out, 40), 0)- return out-}--fn object_path(repo: layout.Repo, oid: bytes.Bytes) str.StringView = trust {- val hex: ref u8 = hex_oid(oid)- val gitp: str.StringView = layout.git_dir(repo)- val objects: str.StringView = files.join(gitp, str.from_cstr(c"objects"))- val dirname: str.StringView = str.view(hex, 2)- val filename: str.StringView = str.view(@ptradd(hex, 2), 38)- val dir: str.StringView = files.join(objects, dirname)- val path: str.StringView = files.join(dir, filename)- files.free_path(dir)- files.free_path(objects)- files.free_path(gitp)- @free(hex as ref void)- return path-}--fn put_decimal(b: mut buf.Buf, v: u64) void = trust {- if v == 0 {- buf.Buf.put_u8(b, 48)- return- }- val tmp: ref u8 = @alloc(24) as ref u8- val n: mut usize = 0- val x: mut u64 = v- for x > 0 {- @store8(@ptradd(tmp, n as i64), (48 + (x % 10)) as u8)- x = x / 10- n++- }- val i: mut usize = n- for i > 0 {- i--- buf.Buf.put_u8(b, @load8(@ptradd(tmp, i as i64)))- }- @free(tmp as ref void)-}--fn kind_name(kind: u8) bytes.Bytes = trust {- if kind == object.KIND_COMMIT {- return bytes.bytes(c"commit", 6)- }- if kind == object.KIND_TREE {- return bytes.bytes(c"tree", 4)- }- if kind == object.KIND_BLOB {- return bytes.bytes(c"blob", 4)- }- return bytes.bytes(c"tag", 3)-}--fn write_loose(- ctx: ref ExportCtx,- kind: u8,- oid: bytes.Bytes,- body: bytes.Bytes-) bool = trust {- val final: str.StringView = object_path(ctx.repo, oid)- if files.exists_file(final) {- files.free_path(final)- return true- }- val hex: ref u8 = hex_oid(oid)- val gitp: str.StringView = layout.git_dir(ctx.repo)- val objects: str.StringView = files.join(gitp, str.from_cstr(c"objects"))- val dirname: str.StringView = str.view(hex, 2)- val objdir: str.StringView = files.join(objects, dirname)- if !files.exists_dir(objdir) {- val _ = files.mkdir_all(objdir)- }- files.free_path(objdir)- files.free_path(objects)- files.free_path(gitp)- @free(hex as ref void)-- val header: mut buf.Buf = buf.new(64)- buf.Buf.put_bytes(header, kind_name(kind))- buf.Buf.put_u8(header, 32)- put_decimal(header, body.len as u64)- buf.Buf.put_u8(header, 0)- buf.Buf.put_bytes(header, body)-- val bound: u64 = compressBound(header.len as u64)- val dst: ref u8 = @alloc(bound as usize) as ref u8- val dst_len: mut u64 = bound- val rc: i32 = compress2(- dst,- dst_len,- header.ptr,- header.len as u64,- 6- )- buf.Buf.free(header)- if rc != 0 {- @free(dst as ref void)- files.free_path(final)- return false- }- val tmpd: str.StringView = layout.tmp_dir(ctx.repo)- val tmpname: str.StringView = files.basename(final)- val tmp: str.StringView = files.join(tmpd, tmpname)- val parent: str.StringView = files.join(layout.git_dir(ctx.repo), str.from_cstr(c"objects"))- val good: bool = nativeio.write_atomic(- tmp,- final,- tmpd,- parent,- bytes.bytes(dst, dst_len as usize)- )- files.free_path(tmp)- files.free_path(tmpd)- files.free_path(parent)- files.free_path(final)- @free(dst as ref void)- return good-}--fn export_blob(ctx: mut ExportCtx, id: objid.Id) option[bytes.Bytes] = trust {- if lazy.is_lazy(id) {- val oid: bytes.Bytes = bytes.Bytes.dup(lazy.git_oid(id))- map_put(ctx.blobs, oid, id)- return some oid- }- val existing = reverse_lookup(ctx.blobs, id)- if existing is some oid {- return some oid- }- val data_opt = content.read_blob(ctx.handles, id, ctx.git, ctx.git_open)- val data: mut bytes.Bytes = bytes.empty()- match data_opt {- some d => {- data = d- }- none => {- ctx.failed = true- return none- }- }- val hash = object.object_hash(object.KIND_BLOB, data)- val oid: mut bytes.Bytes = bytes.empty()- match hash {- some h => {- oid = h- }- none => {- ctx.failed = true- files.free_buffer(data)- return none- }- }- val wrote: bool = write_loose(ctx, object.KIND_BLOB, oid, data)- files.free_buffer(data)- if !wrote {- ctx.failed = true- object.free_digest(oid)- return none- }- map_put(ctx.blobs, oid, id)- return some oid-}--fn entry_key(e: ref tree.TreeEntry) bytes.Bytes = trust {- // Git compares tree names as if directory names ended in '/'.- if e.kind == tree.KIND_SUBTREE {- val out: ref u8 = @alloc(e.name.len + 1) as ref u8- @memcpy(out as ref void, e.name.ptr as ref void, e.name.len)- @store8(@ptradd(out, e.name.len as i64), 47)- return bytes.bytes(out, e.name.len + 1)- }- return e.name-}--fn sort_git_entries(entries: mut list[ref tree.TreeEntry]) void = trust {- val i: mut usize = 1- for i < @len(entries) {- val cur = @get(entries, i)- val c: mut ref tree.TreeEntry = none- if cur is some v {- c = v- }- val j: mut usize = i- for j > 0 {- val prev_o = @get(entries, j - 1)- val prev: mut ref tree.TreeEntry = none- if prev_o is some p {- prev = p- }- val ck: bytes.Bytes = entry_key(c)- val pk: bytes.Bytes = entry_key(prev)- val cmp: i64 = bytes.Bytes.cmp(pk, ck)- if pk.len > prev.name.len {- val pp: mut ref void = pk.ptr as ref void- @free(pp)- }- if ck.len > c.name.len {- val cp: mut ref void = ck.ptr as ref void- @free(cp)- }- if cmp <= 0 {- break- }- @set(entries, j, prev)- j--- }- @set(entries, j, c)- i++- }-}--fn mode_for(kind: u8) bytes.Bytes = trust {- if kind == tree.KIND_EXECUTABLE {- return bytes.bytes(c"100755", 6)- }- if kind == tree.KIND_SYMLINK {- return bytes.bytes(c"120000", 6)- }- if kind == tree.KIND_SUBTREE {- return bytes.bytes(c"40000", 5)- }- if kind == tree.KIND_SUBMODULE {- return bytes.bytes(c"160000", 6)- }- return bytes.bytes(c"100644", 6)-}--fn export_tree(ctx: mut ExportCtx, id: objid.Id) option[bytes.Bytes] = trust {- if ctx.failed {- return none- }- val existing = reverse_lookup(ctx.trees, id)- if existing is some oid {- return some oid- }- val raw_opt = gitmap.load_raw(ctx.repo, id)- if raw_opt is some raw {- val hash = object.object_hash(object.KIND_TREE, raw)- val oid: mut bytes.Bytes = bytes.empty()- match hash {- some h => {- oid = h- }- none => {- files.free_buffer(raw)- ctx.failed = true- return none- }- }- val wrote: bool = write_loose(ctx, object.KIND_TREE, oid, raw)- files.free_buffer(raw)- if !wrote {- ctx.failed = true- object.free_digest(oid)- return none- }- map_put(ctx.trees, oid, id)- return some oid- }- val t_opt = treewalk.read_tree(ctx.handles, id)- val t: mut ref tree.Tree = none- match t_opt {- some x => {- t = x- }- none => {- ctx.failed = true- return none- }- }- val entries: mut list[ref tree.TreeEntry] = lists.new[ref tree.TreeEntry]()- val child_oids: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()- val good: mut bool = true- for e in t.entries {- val child: mut option[bytes.Bytes] = none- if e.kind == tree.KIND_SUBTREE {- child = export_tree(ctx, e.target)- } elif e.kind == tree.KIND_SUBMODULE {- val oid20: bytes.Bytes = bytes.Bytes.dup(bytes.Bytes.slice(- bytes.bytes(e.target.ptr, 32),- 0,- 20- ))- child = some(oid20)- } elif e.kind == tree.KIND_CONFLICT {- ctx.failed = true- good = false- } else {- child = export_blob(ctx, e.target)- }- if child is some co {- @append(- entries,- tree.entry(bytes.Bytes.dup(e.name), e.kind, objid.id(co.ptr))- )- @append(child_oids, co)- } else {- good = false- }- if !good {- break- }- }- tree.free_tree(t)- if !good {- for e in entries {- if e.name.ptr != none {- val np: mut ref void = e.name.ptr as ref void- @free(np)- }- if e.target.ptr != none {- val tp: mut ref void = e.target.ptr as ref void- @free(tp)- }- val ep: mut ref void = e as ref void- @free(ep)- }- @listfree(entries)- for o in child_oids {- object.free_digest(o)- }- @listfree(child_oids)- return none- }- sort_git_entries(entries)- val body: mut buf.Buf = buf.new(@len(entries) * 32 + 8)- val i: mut usize = 0- for i < @len(entries) {- val o = @get(entries, i)- if o is some e {- buf.Buf.put_bytes(body, mode_for(e.kind))- buf.Buf.put_u8(body, 32)- buf.Buf.put_bytes(body, e.name)- buf.Buf.put_u8(body, 0)- buf.Buf.put_bytes(body, bytes.bytes(e.target.ptr, 20))- }- i++- }- val hash = object.object_hash(object.KIND_TREE, buf.Buf.view(body))- val oid_out: mut bytes.Bytes = bytes.empty()- match hash {- some h => {- oid_out = h- }- none => {- good = false- }- }- if good {- good = write_loose(ctx, object.KIND_TREE, oid_out, buf.Buf.view(body))- if good {- map_put(ctx.trees, oid_out, id)- }- }- buf.Buf.free(body)- for e in entries {- if e.name.ptr != none {- val np: mut ref void = e.name.ptr as ref void- @free(np)- }- if e.target.ptr != none {- val tp: mut ref void = e.target.ptr as ref void- @free(tp)- }- val ep: mut ref void = e as ref void- @free(ep)- }- @listfree(entries)- for o in child_oids {- object.free_digest(o)- }- @listfree(child_oids)- if !good {- ctx.failed = true- if oid_out.ptr != none {- object.free_digest(oid_out)- }- return none- }- return some oid_out-}--fn parent_oids(ctx: mut ExportCtx, c: ref commit.Commit) list[bytes.Bytes] = trust {- val out: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()- for p in c.parents {- val g = reverse_lookup(ctx.commits, p)- match g {- some oid => {- @append(out, oid)- }- none => {- ctx.failed = true- }- }- }- return out-}--fn serialize_commit(- ctx: ref ExportCtx,- id: objid.Id,- c: ref commit.Commit,- tree_oid: bytes.Bytes,- parents: list[bytes.Bytes],- is_native: bool-) option[bytes.Bytes] = trust {- val raw_opt = gitmap.load_raw(ctx.repo, id)- if raw_opt is some raw {- val parsed_opt = format.parse_commit(raw)- val use_raw: mut bool = false- if parsed_opt is some parsed {- if bytes.Bytes.eql(parsed.tree, tree_oid) && @len(parsed.parents) == @len(parents) {- use_raw = true- val pi: mut usize = 0- for pi < @len(parents) {- val po = @get(parsed.parents, pi)- if po is some poid {- if !bytes.Bytes.eql(poid, parents_at(parents, pi)) {- use_raw = false- break- }- }- pi++- }- }- format.free_parsed_commit(parsed)- }- if use_raw {- return some raw- }- files.free_buffer(raw)- }-- val extras: mut list[ref prim.KeyValue] = lists.new[ref prim.KeyValue]()- for kv in c.extra {- @append(extras, commit.new_kv(bytes.Bytes.dup(kv.key), bytes.Bytes.dup(kv.value)))- }- if is_native {- val hex: ref u8 = objid.ChangeId.hex(c.change_id)- @append(- extras,- commit.new_kv(- bytes.Bytes.dup(bytes.bytes(c"veins-change-id", 15)),- bytes.Bytes.dup(bytes.bytes(hex, 32))- )- )- @free(hex as ref void)- }- val pc: mut ref format.ParsedCommit = @alloc(@sizeof(format.ParsedCommit)) as ref format.ParsedCommit- pc.tree = tree_oid- pc.parents = lists.new[bytes.Bytes]()- for p in parents {- @append(pc.parents, bytes.Bytes.dup(p))- }- pc.author = c.author- pc.committer = c.committer- pc.message = c.message- pc.extras = extras- pc.change_id = bytes.empty()- pc.canonical = true- val body: bytes.Bytes = format.serialize_commit(pc)- // ParsedCommit owns parents/extras here, not the borrowed commit fields.- for p in pc.parents {- if p.ptr != none {- val pp: mut ref void = p.ptr as ref void- @free(pp)- }- }- @listfree(pc.parents)- for kv in extras {- if kv.key.ptr != none {- val kp: mut ref void = kv.key.ptr as ref void- @free(kp)- }- if kv.value.ptr != none {- val vp: mut ref void = kv.value.ptr as ref void- @free(vp)- }- val xp: mut ref void = kv as ref void- @free(xp)- }- @listfree(extras)- @free(pc as ref void)- return some body-}--fn parents_at(xs: list[bytes.Bytes], i: usize) bytes.Bytes = trust {- val o = @get(xs, i)- if o is some b {- return b- }- return bytes.empty()-}--fn export_commit(ctx: mut ExportCtx, id: objid.Id) bool = trust {- if ctx.failed {- return false- }- val existing = reverse_lookup(ctx.commits, id)- if existing is some _ {- return true- }- val lc_opt = graph.load_commit(ctx.handles, id)- val lc: mut ref graph.LoadedCommit = none- match lc_opt {- some x => {- lc = x- }- none => {- ctx.failed = true- return false- }- }- val tree_opt = export_tree(ctx, lc.c.root_tree)- val tree_oid: mut bytes.Bytes = bytes.empty()- match tree_opt {- some t => {- tree_oid = t- }- none => {- graph.free_loaded(lc)- return false- }- }- val parents: list[bytes.Bytes] = parent_oids(ctx, lc.c)- val is_native: bool = gitmap.is_native(ctx.native, id)- val body_opt = serialize_commit(ctx, id, lc.c, tree_oid, parents, is_native)- val body: mut bytes.Bytes = bytes.empty()- match body_opt {- some b => {- body = b- }- none => {- ctx.failed = true- }- }- val status: mut bool = !ctx.failed- val oid_out: mut bytes.Bytes = bytes.empty()- if status {- val hash = object.object_hash(object.KIND_COMMIT, body)- match hash {- some h => {- oid_out = h- }- none => {- status = false- }- }- }- if status {- status = write_loose(ctx, object.KIND_COMMIT, oid_out, body)- if status {- map_put(ctx.commits, oid_out, id)- }- }- if body.ptr != none {- files.free_buffer(body)- }- if tree_oid.ptr != none {- object.free_digest(tree_oid)- }- for p in parents {- object.free_digest(p)- }- @listfree(parents)- if oid_out.ptr != none {- object.free_digest(oid_out)- }- graph.free_loaded(lc)- if !status {- ctx.failed = true- }- return status-}--fn ordered_commits(- handles: list[ref store.Handle],- roots: list[objid.Id]-) list[objid.Id] = trust {- val all_ids: list[objid.Id] = graph.collect(handles, roots)- val visited: mut list[objid.Id] = lists.new[objid.Id]()- val ordered: mut list[objid.Id] = lists.new[objid.Id]()- val stack: mut list[ref Mark] = lists.new[ref Mark]()- val i0: mut usize = 0- for i0 < @len(all_ids) {- val o = @get(all_ids, i0)- if o is some id {- val m: mut ref Mark = @alloc(@sizeof(Mark)) as ref Mark- m.id = id- m.expanded = false- @append(stack, m)- }- i0++- }- for @len(stack) > 0 {- val m: mut ref Mark = @remove(stack, @len(stack) - 1)- if contains(visited, m.id) {- @free(m as ref void)- continue- }- if !m.expanded {- m.expanded = true- @append(stack, m)- val lc_opt = graph.load_commit(handles, m.id)- if lc_opt is some lc {- val pi: mut usize = @len(lc.c.parents)- for pi > 0 {- pi--- val p = @get(lc.c.parents, pi)- if p is some pid {- if !contains(visited, pid) {- val pm: mut ref Mark = @alloc(@sizeof(Mark)) as ref Mark- pm.id = copy_id(pid)- pm.expanded = false- @append(stack, pm)- }- }- }- graph.free_loaded(lc)- }- } else {- @append(visited, copy_id(m.id))- @append(ordered, copy_id(m.id))- @free(m as ref void)- }- }- @listfree(stack)- free_ids(visited)- free_ids(all_ids)- return ordered-}--fn exportable_target(handles: list[ref store.Handle], id: objid.Id) option[objid.Id] = trust {- val current: mut objid.Id = copy_id(id)- val steps: mut usize = 0- for steps < 100000 {- val lc_opt = graph.load_commit(handles, current)- if lc_opt is none {- if current.ptr != none {- @free(current.ptr as ref void)- }- return none- }- val lc: mut ref graph.LoadedCommit = none- if lc_opt is some x {- lc = x- }- val conflicted: bool = treewalk.conflicted(handles, lc.c.root_tree)- if !conflicted {- val out: objid.Id = copy_id(current)- graph.free_loaded(lc)- if current.ptr != none {- @free(current.ptr as ref void)- }- return some out- }- val next: mut option[objid.Id] = none- if @len(lc.c.parents) > 0 {- val p = @get(lc.c.parents, 0)- if p is some pid {- next = some(copy_id(pid))- }- }- graph.free_loaded(lc)- if current.ptr != none {- @free(current.ptr as ref void)- }- match next {- some nid => {- current = nid- }- none => {- return none- }- }- steps++- }- return none-}--fn write_ref(ctx: ref ExportCtx, ref_name: bytes.Bytes, oid: bytes.Bytes) bool = trust {- val gitp: str.StringView = layout.git_dir(ctx.repo)- val refstr: str.StringView = files.to_view(ref_name)- val final: str.StringView = files.join(gitp, refstr)- val dir0: str.StringView = files.join(gitp, str.from_cstr(c"refs"))- val dir: mut str.StringView = dir0- val slash: mut i64 = -1- val i: mut usize = 0- for i < final.len {- if @load8(@ptradd(final.ptr, i as i64)) == 47 {- slash = i as i64- }- i++- }- if slash > 0 {- dir = str.view(final.ptr, slash as usize)- if !files.exists_dir(dir) {- val _ = files.mkdir_all(dir)- }- }- val hex: ref u8 = hex_oid(oid)- val line: ref u8 = @fmtalloc("{s}\n", {str.from_cstr(hex)})- val tmpd: str.StringView = layout.tmp_dir(ctx.repo)- val tmpname: ref u8 = @fmtalloc("{s}.tmp", {str.from_cstr(hex)})- val tmp_name_view: str.StringView = str.from_cstr(tmpname)- val tmp: str.StringView = files.join(tmpd, tmp_name_view)- val good: bool = nativeio.write_atomic(tmp, final, tmpd, dir, bytes.from_cstr(line))- files.free_path(tmp)- files.free_path(tmp_name_view)- files.free_path(tmpd)- files.free_path(dir0)- files.free_path(final)- files.free_path(gitp)- @free(hex as ref void)- @free(line as ref void)- return good-}--pub fn run(repo: layout.Repo) i32 = trust {- val gitp: str.StringView = layout.git_dir(repo)- if !files.exists_dir(gitp) {- msg.error_prefix()- stdio.eprint("no git mirror; run `vn git import` first\n", {})- files.free_path(gitp)- return 1- }- val git_opt = object.open(gitp)- files.free_path(gitp)- val git_repo: mut object.GitRepo = @zeroed- val git_open: mut bool = false- match git_opt {- ok g => {- git_repo = g- git_open = true- }- err _ => {- }- }-- val commits_opt = gitmap.load_map(repo, str.from_cstr(c"commits"))- val trees_opt = gitmap.load_map(repo, str.from_cstr(c"trees"))- val blobs_opt = gitmap.load_map(repo, str.from_cstr(c"blobs"))- val commits: mut oidmap.OidMap = oidmap.new(64)- val trees: mut oidmap.OidMap = oidmap.new(64)- val blobs: mut oidmap.OidMap = oidmap.new(64)- match commits_opt {- ok m => {- commits = m- }- err _ => {- }- }- match trees_opt {- ok m => {- trees = m- }- err _ => {- }- }- match blobs_opt {- ok m => {- blobs = m- }- err _ => {- }- }- val native_ids: list[objid.Id] = gitmap.load_native(repo)- val st: store.Store = store.open_all(repo)- val ctx: mut ExportCtx = ExportCtx{- repo: repo,- handles: st.handles,- commits: commits,- trees: trees,- blobs: blobs,- native: native_ids,- git: git_repo,- git_open: git_open,- failed: false- }- val v_opt = state.current_view(repo, st.handles)- val v: mut ref view.View = none- match v_opt {- some x => {- v = x- }- none => {- store.close(st)- oidmap.free(commits)- oidmap.free(trees)- oidmap.free(blobs)- free_ids(native_ids)- msg.error_prefix()- stdio.eprint("no operation state\n", {})- return 1- }- }- val roots: mut list[objid.Id] = lists.new[objid.Id]()- val resolved_bookmarks: mut list[ref view.Bookmark] = lists.new[ref view.Bookmark]()- val mut_skipped: mut usize = 0- for bm in v.bookmarks {- val target = first_target(bm.targets.adds)- if target is some tid {- val exp = exportable_target(st.handles, tid)- match exp {- some x => {- if !contains(roots, x) {- @append(roots, copy_id(x))- }- val nb: mut ref view.Bookmark = @alloc(@sizeof(view.Bookmark)) as ref view.Bookmark- nb.name = bytes.Bytes.dup(bm.name)- nb.targets = view.empty_target_set()- @append(nb.targets.adds, copy_id(x))- @append(resolved_bookmarks, nb)- if x.ptr != none {- @free(x.ptr as ref void)- }- }- none => {- mut_skipped++- }- }- }- }- val resolved_tags: mut list[ref view.TagRef] = lists.new[ref view.TagRef]()- for t in v.tags {- val exp = exportable_target(st.handles, t.target)- match exp {- some x => {- if !contains(roots, x) {- @append(roots, copy_id(x))- }- val nt: mut ref view.TagRef = @alloc(@sizeof(view.TagRef)) as ref view.TagRef- nt.name = bytes.Bytes.dup(t.name)- nt.target = copy_id(x)- @append(resolved_tags, nt)- if x.ptr != none {- @free(x.ptr as ref void)- }- }- none => {- mut_skipped++- }- }- }- val ordered: list[objid.Id] = ordered_commits(st.handles, roots)- val exported: mut usize = 0- for id in ordered {- val had = reverse_lookup(commits, id)- if had is none {- if export_commit(ctx, id) {- exported++- }- } else {- if had is some oid {- object.free_digest(oid)- }- }- if ctx.failed {- break- }- }- val status: mut i32 = 0- if ctx.failed {- msg.error_prefix()- stdio.eprint("git export failed\n", {})- status = 1- } else {- for bm in resolved_bookmarks {- val target = first_target(bm.targets.adds)- if target is some tid {- val g = reverse_lookup(commits, tid)- if g is some oid {- val full: ref u8 = @alloc(11 + bm.name.len + 1) as ref u8- @memcpy(full as ref void, c"refs/heads/", 11)- @memcpy(@ptradd(full, 11) as ref void, bm.name.ptr as ref void, bm.name.len)- @store8(@ptradd(full, (11 + bm.name.len) as i64), 0)- val full_b: bytes.Bytes = bytes.from_cstr(full)- if !write_ref(ctx, full_b, oid) {- status = 1- }- @free(full as ref void)- object.free_digest(oid)- }- }- }- for t in resolved_tags {- val g = reverse_lookup(commits, t.target)- if g is some oid {- val full: ref u8 = @alloc(10 + t.name.len + 1) as ref u8- @memcpy(full as ref void, c"refs/tags/", 10)- @memcpy(@ptradd(full, 10) as ref void, t.name.ptr as ref void, t.name.len)- @store8(@ptradd(full, (10 + t.name.len) as i64), 0)- val full_b: bytes.Bytes = bytes.from_cstr(full)- if !write_ref(ctx, full_b, oid) {- status = 1- }- @free(full as ref void)- object.free_digest(oid)- }- }- if mut_skipped > 0 {- msg.warning_prefix()- stdio.eprint("skipped {d} conflicted ref(s)\n", {mut_skipped})- }- }- if status == 0 {- val sc = gitmap.save_map(repo, str.from_cstr(c"commits"), commits)- val stree = gitmap.save_map(repo, str.from_cstr(c"trees"), trees)- val sblob = gitmap.save_map(repo, str.from_cstr(c"blobs"), blobs)- if !sc || !stree || !sblob {- msg.error_prefix()- stdio.eprint("failed to write git mapping tables\n", {})- status = 1- }- }- msg.info_prefix()- stdio.print("exported {d} commits\n", {exported})- view.free_view(v)- free_ids(roots)- free_ids(ordered)- for bm in resolved_bookmarks {- if bm.name.ptr != none {- val np: mut ref void = bm.name.ptr as ref void- @free(np)- }- for x in bm.targets.adds {- if x.ptr != none {- val xp: mut ref void = x.ptr as ref void- @free(xp)- }- }- for x in bm.targets.removes {- if x.ptr != none {- val xp2: mut ref void = x.ptr as ref void- @free(xp2)- }- }- @listfree(bm.targets.adds)- @listfree(bm.targets.removes)- val bp: mut ref void = bm as ref void- @free(bp)- }- @listfree(resolved_bookmarks)- for t in resolved_tags {- if t.name.ptr != none {- val np: mut ref void = t.name.ptr as ref void- @free(np)- }- if t.target.ptr != none {- val tp: mut ref void = t.target.ptr as ref void- @free(tp)- }- val xp: mut ref void = t as ref void- @free(xp)- }- @listfree(resolved_tags)- free_ids(native_ids)- store.close(st)- oidmap.free(commits)- oidmap.free(trees)- oidmap.free(blobs)- if git_open {- object.free(git_repo)- }- return status-}--fn first_target(adds: list[objid.Id]) option[objid.Id] = trust {- if @len(adds) > 0 {- return @get(adds, 0)- }- return none-}--- a/src/src/git/format.sx+++ /dev/null@@ -1,656 +0,0 @@-/// Parsing and canonical serialization of git commit, tree, and tag objects.--val bytes = use("../core/bytes.sx")-val buf = use("../core/buf.sx")-val prim = use("../core/primitives.sx")-val lists = use("../core/lists.sx")-val tree = use("../object/tree.sx")-val object = use("object.sx")--pub type RawTreeEntry = {- mode: mut bytes.Bytes- name: mut bytes.Bytes- oid: mut bytes.Bytes- canonical: mut bool-}--pub type ParsedTree = {- entries: mut list[ref RawTreeEntry]- canonical: mut bool-}--pub type ParsedTag = {- target: mut bytes.Bytes- target_kind: mut u8-}--pub type ParsedCommit = {- tree: mut bytes.Bytes- parents: mut list[bytes.Bytes]- author: mut prim.Sig- committer: mut prim.Sig- message: mut bytes.Bytes- extras: mut list[ref prim.KeyValue]- change_id: mut bytes.Bytes- canonical: mut bool-}--fn hex_digit(n: u8) u8 = trust {- if n < 10 {- return (48 + n) as u8- }- return (87 + n) as u8-}--fn hex_value(c: u8) i32 = trust {- 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-}--pub fn oid_from_hex(hex: bytes.Bytes) option[bytes.Bytes] = trust {- if hex.len != 40 {- return none- }- val out: ref u8 = @alloc(20) as ref u8- val i: mut usize = 0- for i < 20 {- val hi: i32 = hex_value(bytes.Bytes.at(hex, i * 2))- val lo: i32 = hex_value(bytes.Bytes.at(hex, i * 2 + 1))- if hi < 0 || lo < 0 {- @free(out as ref void)- return none- }- @store8(@ptradd(out, i as i64), ((hi * 16 + lo) as u8))- i++- }- return some bytes.bytes(out, 20)-}--fn put_hex_id(b: mut buf.Buf, oid: bytes.Bytes) void = trust {- val i: mut usize = 0- for i < 20 {- val v: u8 = bytes.Bytes.at(oid, i)- buf.Buf.put_u8(b, hex_digit(v >> 4))- buf.Buf.put_u8(b, hex_digit(v & 15))- i++- }-}--fn parse_u64(text: bytes.Bytes) option[u64] = trust {- if text.len == 0 {- return none- }- val v: mut u64 = 0- val i: mut usize = 0- for i < text.len {- val c: u8 = bytes.Bytes.at(text, i)- if c < 48 || c > 57 {- return none- }- v = v * 10 + (c - 48) as u64- i++- }- return some v-}--fn parse_i64(text: bytes.Bytes) option[i64] = trust {- if text.len == 0 {- return none- }- val negative: bool = bytes.Bytes.at(text, 0) == 45- val start: mut usize = 0- if negative {- start = 1- }- val mag_opt = parse_u64(bytes.Bytes.slice(text, start, text.len))- val mag: mut u64 = 0- match mag_opt {- some v => {- mag = v- }- none => {- return none- }- }- if mag > 9223372036854775807 {- return none- }- val signed: mut i64 = mag as i64- if negative {- signed = 0 - signed- }- return some signed-}--fn parse_tz(text: bytes.Bytes) option[i16] = trust {- if text.len != 5 {- return none- }- val sign: u8 = bytes.Bytes.at(text, 0)- if sign != 43 && sign != 45 {- return none- }- val hours_opt = parse_u64(bytes.Bytes.slice(text, 1, 3))- val mins_opt = parse_u64(bytes.Bytes.slice(text, 3, 5))- val hours: mut u64 = 0- val mins: mut u64 = 0- match hours_opt {- some v => {- hours = v- }- none => {- return none- }- }- match mins_opt {- some v => {- mins = v- }- none => {- return none- }- }- val total: i64 = (hours * 60 + mins) as i64- if total > 32767 {- return none- }- val tz: mut i16 = total as i16- if sign == 45 {- tz = 0 - tz- }- return some tz-}--fn last_index_of(value: bytes.Bytes, needle: u8, end: usize) i64 = trust {- val i: mut i64 = end as i64 - 1- for i >= 0 {- if bytes.Bytes.at(value, i as usize) == needle {- return i- }- i--- }- return -1-}--/// Parse "Name <email> seconds timezone".-pub fn parse_sig(value: bytes.Bytes) option[prim.Sig] = trust {- val tz_space: i64 = last_index_of(value, 32, value.len)- if tz_space < 0 {- return none- }- val sec_space: i64 = last_index_of(value, 32, tz_space as usize)- if sec_space < 0 {- return none- }- val sec_opt = parse_i64(bytes.Bytes.slice(value, sec_space as usize + 1, tz_space as usize))- val tz_opt = parse_tz(bytes.Bytes.slice(value, tz_space as usize + 1, value.len))- val seconds: mut i64 = 0- val tz: mut i16 = 0- match sec_opt {- some v => {- seconds = v- }- none => {- return none- }- }- match tz_opt {- some v => {- tz = v- }- none => {- return none- }- }- val ident: bytes.Bytes = bytes.Bytes.slice(value, 0, sec_space as usize)- val lt: i64 = last_index_of(ident, 60, ident.len)- if lt < 0 {- return none- }- val gt: i64 = last_index_of(ident, 62, ident.len)- if gt <= lt {- return none- }- val name_end: usize = lt as usize- val email_start: usize = lt as usize + 1- val email_end: usize = gt as usize- val raw_name: bytes.Bytes = bytes.Bytes.slice(ident, 0, name_end)- val name: mut bytes.Bytes = raw_name- if raw_name.len > 0 && bytes.Bytes.at(raw_name, raw_name.len - 1) == 32 {- name = bytes.Bytes.slice(raw_name, 0, raw_name.len - 1)- }- return some prim.Sig{- name: name,- email: bytes.Bytes.slice(ident, email_start, email_end),- seconds: seconds,- tz_min: tz- }-}--fn put_sig(b: mut buf.Buf, sig: prim.Sig) void = trust {- buf.Buf.put_bytes(b, sig.name)- buf.Buf.put_u8(b, 32)- buf.Buf.put_u8(b, 60)- buf.Buf.put_bytes(b, sig.email)- buf.Buf.put_u8(b, 62)- buf.Buf.put_u8(b, 32)- val sec_text: ref u8 = @fmtalloc("{d}", {sig.seconds})- buf.Buf.put_bytes(b, bytes.from_cstr(sec_text))- @free(sec_text as ref void)- buf.Buf.put_u8(b, 32)- val minutes: i64 = sig.tz_min as i64- val abs_min: mut i64 = minutes- if minutes < 0 {- buf.Buf.put_u8(b, 45)- abs_min = -minutes- } else {- buf.Buf.put_u8(b, 43)- }- val hh: i64 = abs_min / 60- val mm: i64 = abs_min % 60- buf.Buf.put_u8(b, (48 + hh / 10) as u8)- buf.Buf.put_u8(b, (48 + hh % 10) as u8)- buf.Buf.put_u8(b, (48 + mm / 10) as u8)- buf.Buf.put_u8(b, (48 + mm % 10) as u8)-}--fn find_blank_line(data: bytes.Bytes) i64 = trust {- if data.len < 2 {- return -1- }- val i: mut usize = 0- for i + 1 < data.len {- if bytes.Bytes.at(data, i) == 10 && bytes.Bytes.at(data, i + 1) == 10 {- return i as i64- }- i++- }- return -1-}--fn starts_with_space(line: bytes.Bytes) bool = trust {- return line.len > 0 && bytes.Bytes.at(line, 0) == 32-}--fn parse_header_line(line: bytes.Bytes) option[prim.KeyValue] = trust {- val space: mut usize = 0- for space < line.len && bytes.Bytes.at(line, space) != 32 {- space++- }- if space == 0 || space >= line.len {- return none- }- val key: bytes.Bytes = bytes.Bytes.slice(line, 0, space)- val value: bytes.Bytes = bytes.Bytes.slice(line, space + 1, line.len)- return some prim.KeyValue{key: key, value: value}-}--fn new_kv(key: bytes.Bytes, value: bytes.Bytes) ref prim.KeyValue = trust {- val kv: mut ref prim.KeyValue = @alloc(@sizeof(prim.KeyValue)) as ref prim.KeyValue- kv.key = key- kv.value = value- return kv-}--fn find_line_end(data: bytes.Bytes, start: usize, end: usize) usize = trust {- val i: mut usize = start- for i < end && bytes.Bytes.at(data, i) != 10 {- i++- }- return i-}--pub fn parse_commit(body: bytes.Bytes) option[ref ParsedCommit] = trust {- val blank: i64 = find_blank_line(body)- if blank < 0 {- return none- }- val header_end: usize = blank as usize- val message: bytes.Bytes = bytes.Bytes.slice(body, header_end + 2, body.len)- val out: mut ref ParsedCommit = @alloc(@sizeof(ParsedCommit)) as ref ParsedCommit- out.tree = bytes.empty()- out.parents = lists.new[bytes.Bytes]()- out.author = prim.Sig{name: bytes.empty(), email: bytes.empty(), seconds: 0, tz_min: 0}- out.committer = prim.Sig{name: bytes.empty(), email: bytes.empty(), seconds: 0, tz_min: 0}- out.message = message- out.extras = lists.new[ref prim.KeyValue]()- out.change_id = bytes.empty()- out.canonical = true-- val last_extra: mut ref prim.KeyValue = none- val last_extra_start: mut usize = 0- val pos: mut usize = 0- for pos < header_end {- val line_end: usize = find_line_end(body, pos, header_end)- val line: bytes.Bytes = bytes.Bytes.slice(body, pos, line_end)- if starts_with_space(line) {- if last_extra == none {- out.canonical = false- } else {- last_extra.value = bytes.Bytes.slice(body, last_extra_start, line_end)- }- } else {- last_extra = none- val kv_opt = parse_header_line(line)- match kv_opt {- some kv => {- if bytes.Bytes.eql(kv.key, bytes.bytes(c"tree", 4)) {- val oid_opt = oid_from_hex(kv.value)- match oid_opt {- some oid => {- out.tree = oid- }- none => {- out.canonical = false- }- }- } elif bytes.Bytes.eql(kv.key, bytes.bytes(c"parent", 6)) {- val oid_opt2 = oid_from_hex(kv.value)- match oid_opt2 {- some oid => {- @append(out.parents, oid)- }- none => {- out.canonical = false- }- }- } elif bytes.Bytes.eql(kv.key, bytes.bytes(c"author", 6)) {- val sig_opt = parse_sig(kv.value)- match sig_opt {- some sig => {- out.author = sig- }- none => {- out.canonical = false- }- }- } elif bytes.Bytes.eql(kv.key, bytes.bytes(c"committer", 9)) {- val sig_opt2 = parse_sig(kv.value)- match sig_opt2 {- some sig => {- out.committer = sig- }- none => {- out.canonical = false- }- }- } elif bytes.Bytes.eql(kv.key, bytes.bytes(c"veins-change-id", 15)) {- if kv.value.len == 32 {- val cid: ref u8 = @alloc(16) as ref u8- val j: mut usize = 0- for j < 16 {- val hi: i32 = hex_value(bytes.Bytes.at(kv.value, j * 2))- val lo: i32 = hex_value(bytes.Bytes.at(kv.value, j * 2 + 1))- if hi < 0 || lo < 0 {- @free(cid as ref void)- out.canonical = false- break- }- @store8(@ptradd(cid, j as i64), ((hi * 16 + lo) as u8))- j++- }- if j == 16 {- out.change_id = bytes.bytes(cid, 16)- }- } else {- out.canonical = false- }- } else {- val extra: ref prim.KeyValue = new_kv(kv.key, kv.value)- @append(out.extras, extra)- last_extra = extra- last_extra_start = pos + kv.key.len + 1- }- }- none => {- out.canonical = false- }- }- }- pos = line_end + 1- }- return some out-}--pub fn free_parsed_commit(c: ref ParsedCommit) void = trust {- for p in c.parents {- if p.ptr != none {- val pp: mut ref void = p.ptr as ref void- @free(pp)- }- }- @listfree(c.parents)- if c.change_id.ptr != none {- @free(c.change_id.ptr as ref void)- }- for kv in c.extras {- val kp: mut ref void = kv as ref void- @free(kp)- }- @listfree(c.extras)- @free(c as ref void)-}--pub fn serialize_commit(c: ref ParsedCommit) bytes.Bytes = trust {- val b: mut buf.Buf = buf.new(c.message.len + 256)- buf.Buf.put_bytes(b, bytes.bytes(c"tree ", 5))- put_hex_id(b, c.tree)- buf.Buf.put_u8(b, 10)- for p in c.parents {- buf.Buf.put_bytes(b, bytes.bytes(c"parent ", 7))- put_hex_id(b, p)- buf.Buf.put_u8(b, 10)- }- buf.Buf.put_bytes(b, bytes.bytes(c"author ", 7))- put_sig(b, c.author)- buf.Buf.put_u8(b, 10)- buf.Buf.put_bytes(b, bytes.bytes(c"committer ", 10))- put_sig(b, c.committer)- buf.Buf.put_u8(b, 10)- for kv in c.extras {- buf.Buf.put_bytes(b, kv.key)- buf.Buf.put_u8(b, 32)- buf.Buf.put_bytes(b, kv.value)- buf.Buf.put_u8(b, 10)- }- buf.Buf.put_u8(b, 10)- buf.Buf.put_bytes(b, c.message)- val out: bytes.Bytes = bytes.Bytes.dup(buf.Buf.view(b))- buf.Buf.free(b)- return out-}--pub fn canonical_commit_bytes(body: bytes.Bytes) option[bytes.Bytes] = trust {- val parsed_opt = parse_commit(body)- match parsed_opt {- some c => {- val out: bytes.Bytes = serialize_commit(c)- val same: bool = bytes.Bytes.eql(out, body)- free_parsed_commit(c)- if !same {- val op: mut ref void = out.ptr as ref void- @free(op)- return none- }- return some out- }- none => {- return none- }- }-}--pub fn parse_tree(body: bytes.Bytes) option[ref ParsedTree] = trust {- val out: mut ref ParsedTree = @alloc(@sizeof(ParsedTree)) as ref ParsedTree- out.entries = lists.new[ref RawTreeEntry]()- out.canonical = true- val pos: mut usize = 0- for pos < body.len {- val mode_start: usize = pos- for pos < body.len && bytes.Bytes.at(body, pos) != 32 {- pos++- }- if pos >= body.len {- out.canonical = false- break- }- val mode: bytes.Bytes = bytes.Bytes.slice(body, mode_start, pos)- pos++- val name_start: usize = pos- for pos < body.len && bytes.Bytes.at(body, pos) != 0 {- pos++- }- if pos >= body.len {- out.canonical = false- break- }- val name: bytes.Bytes = bytes.Bytes.slice(body, name_start, pos)- pos++- if pos + 20 > body.len {- out.canonical = false- break- }- val oid: bytes.Bytes = bytes.Bytes.slice(body, pos, pos + 20)- pos = pos + 20- val e: mut ref RawTreeEntry = @alloc(@sizeof(RawTreeEntry)) as ref RawTreeEntry- e.mode = mode- e.name = name- e.oid = oid- e.canonical = canonical_mode(mode)- if !e.canonical {- out.canonical = false- }- @append(out.entries, e)- }- if pos != body.len {- out.canonical = false- }- return some out-}--fn canonical_mode(mode: bytes.Bytes) bool = trust {- if bytes.Bytes.eql(mode, bytes.bytes(c"100644", 6)) {- return true- }- if bytes.Bytes.eql(mode, bytes.bytes(c"100755", 6)) {- return true- }- if bytes.Bytes.eql(mode, bytes.bytes(c"120000", 6)) {- return true- }- if bytes.Bytes.eql(mode, bytes.bytes(c"40000", 5)) {- return true- }- if bytes.Bytes.eql(mode, bytes.bytes(c"160000", 6)) {- return true- }- return false-}--pub fn mode_kind(mode: bytes.Bytes) u8 = trust {- if bytes.Bytes.eql(mode, bytes.bytes(c"40000", 5))- || bytes.Bytes.eql(mode, bytes.bytes(c"040000", 6)) {- return tree.KIND_SUBTREE- }- if bytes.Bytes.eql(mode, bytes.bytes(c"120000", 6)) {- return tree.KIND_SYMLINK- }- if bytes.Bytes.eql(mode, bytes.bytes(c"160000", 6)) {- return tree.KIND_SUBMODULE- }- if bytes.Bytes.eql(mode, bytes.bytes(c"100755", 6)) {- return tree.KIND_EXECUTABLE- }- return tree.KIND_FILE-}--fn entry_at(entries: list[ref RawTreeEntry], i: usize) mut ref RawTreeEntry = trust {- val o = @get(entries, i)- if o is some e {- return e- }- assert false- return none-}---/// Sort entries by plain name (veins' tree order).-pub fn sort_raw_entries(entries: mut list[ref RawTreeEntry]) void = trust {- val n: usize = @len(entries)- val i: mut usize = 1- for i < n {- val cur = entry_at(entries, i)- val j: mut usize = i- for j > 0 {- val prev = entry_at(entries, j - 1)- if bytes.Bytes.cmp(prev.name, cur.name) <= 0 {- break- }- @set(entries, j, prev)- j--- }- @set(entries, j, cur)- i++- }-}--pub fn free_parsed_tree(t: ref ParsedTree) void = trust {- for e in t.entries {- val ep: mut ref void = e as ref void- @free(ep)- }- @listfree(t.entries)- @free(t as ref void)-}--pub fn parse_tag(body: bytes.Bytes) option[ParsedTag] = trust {- val out: mut ref ParsedTag = @alloc(@sizeof(ParsedTag)) as ref ParsedTag- out.target = bytes.empty()- out.target_kind = 0- val pos: mut usize = 0- for pos < body.len {- val line_end: usize = find_line_end(body, pos, body.len)- val line: bytes.Bytes = bytes.Bytes.slice(body, pos, line_end)- if line.len == 0 {- break- }- val kv_opt = parse_header_line(line)- if kv_opt is some kv {- if bytes.Bytes.eql(kv.key, bytes.bytes(c"object", 6)) {- val oid_opt = oid_from_hex(kv.value)- if oid_opt is some oid {- out.target = oid- }- } elif bytes.Bytes.eql(kv.key, bytes.bytes(c"type", 4)) {- if bytes.Bytes.eql(kv.value, bytes.bytes(c"commit", 6)) {- out.target_kind = object.KIND_COMMIT- } elif bytes.Bytes.eql(kv.value, bytes.bytes(c"tree", 4)) {- out.target_kind = object.KIND_TREE- } elif bytes.Bytes.eql(kv.value, bytes.bytes(c"blob", 4)) {- out.target_kind = object.KIND_BLOB- } elif bytes.Bytes.eql(kv.value, bytes.bytes(c"tag", 3)) {- out.target_kind = object.KIND_TAG- }- }- }- pos = line_end + 1- }- return some out-}--pub fn free_parsed_tag(t: ref ParsedTag) void = trust {- if t.target.ptr != none {- val tp: mut ref void = t.target.ptr as ref void- @free(tp)- }- val tq: mut ref void = t as ref void- @free(tq)-}--- a/src/src/git/import.sx+++ /dev/null@@ -1,1246 +0,0 @@-lib "z"--/// Import a git object graph into the veins store and record an operation.--val str = use("std/string")-val stdio = use("std/stdio")-val msg = use("../core/msg.sx")-val os = use("std/os")-val time = use("std/time")-val bytes = use("../core/bytes.sx")-val buf = use("../core/buf.sx")-val lists = use("../core/lists.sx")-val prim = use("../core/primitives.sx")-val b3 = use("../crypto/blake3.sx")-val objid = use("../object/id.sx")-val types = use("../object/types.sx")-val tree = use("../object/tree.sx")-val commit = use("../object/commit.sx")-val operation = use("../object/operation.sx")-val view = use("../object/view.sx")-val layout = use("../store/layout.sx")-val store = use("../store/store.sx")-val writer = use("../store/writer.sx")-val state = use("../store/state.sx")-val files = use("../io/files.sx")-val object = use("object.sx")-val lazy = use("lazy.sx")-val format = use("format.sx")-val refs = use("refs.sx")-val oidmap = use("oidmap.sx")-val gitmap = use("map.sx")---pub type ImportStats = {- commits: mut usize- trees: mut usize- blobs: mut usize-}--type ImportNamedTarget = {- name: mut bytes.Bytes- oid: mut bytes.Bytes-}--type ImportCommitRec = {- oid: mut bytes.Bytes- body: mut bytes.Bytes- parsed: mut ref format.ParsedCommit-}--type ImportRawSave = {- id: mut objid.Id- body: mut bytes.Bytes-}--type ImportCtx = {- git: object.GitRepo- commits_map: mut oidmap.OidMap- trees_map: mut oidmap.OidMap- blobs_map: mut oidmap.OidMap- raw_saves: mut list[ref ImportRawSave]- new_commits: mut usize- new_trees: mut usize- new_blobs: mut usize- writer: mut ref writer.Writer-}--fn put_usize(map: mut oidmap.OidMap, oid: bytes.Bytes, value: usize) void = trust {- val v: ref u8 = @alloc(8) as ref u8- @store64(v as ref void, value as i64)- oidmap.put(map, oid, bytes.bytes(v, 8))- @free(v as ref void)-}--fn get_usize(map: oidmap.OidMap, oid: bytes.Bytes) option[usize] = trust {- val got = oidmap.get(map, oid)- match got {- some v => {- return some (@load64(v.ptr as ref void) as usize)- }- none => {- return none- }- }-}--fn get_id(map: oidmap.OidMap, oid: bytes.Bytes) option[objid.Id] = trust {- val got = oidmap.get(map, oid)- match got {- some v => {- return some objid.id(v.ptr)- }- none => {- return none- }- }-}--fn put_id(map: mut oidmap.OidMap, oid: bytes.Bytes, id: objid.Id) void = trust {- oidmap.put(map, oid, bytes.bytes(id.ptr, 32))-}--fn dup_id(id: objid.Id) objid.Id = trust {- val out: ref u8 = @alloc(32) as ref u8- @memcpy(out as ref void, id.ptr as ref void, 32)- return objid.id(out)-}--fn append_object(ctx: mut ImportCtx, kind: u8, body: bytes.Bytes) objid.Id = trust {- return writer.add(ctx.writer, kind, body)-}--fn derive_change_id(oid: bytes.Bytes) objid.ChangeId = trust {- val b: mut buf.Buf = buf.new(48)- buf.Buf.put_raw(b, c"veins/change", 12)- buf.Buf.put_bytes(b, oid)- val out: ref u8 = @alloc(32) as ref u8- b3.hash(b.ptr, b.len, out)- buf.Buf.free(b)- return objid.change_id(out)-}--fn peel_to_commit(git: object.GitRepo, start: bytes.Bytes) option[bytes.Bytes] = trust {- val current: mut bytes.Bytes = bytes.Bytes.dup(start)- for {- val obj_opt = object.read_fast(git, current)- val obj: mut object.Object = object.Object{- kind: 0,- body: bytes.empty(),- alloc: bytes.empty()- }- match obj_opt {- ok o => {- obj = o- }- err _ => {- val cp: mut ref void = current.ptr as ref void- @free(cp)- return none- }- }- if obj.kind == object.KIND_COMMIT {- object.free_object(obj)- return some current- }- if obj.kind != object.KIND_TAG {- object.free_object(obj)- val cp2: mut ref void = current.ptr as ref void- @free(cp2)- return none- }- val parsed_opt = format.parse_tag(obj.body)- val parsed: mut ref format.ParsedTag = none- match parsed_opt {- some t => {- parsed = t- }- none => {- object.free_object(obj)- val cp3: mut ref void = current.ptr as ref void- @free(cp3)- return none- }- }- val next: mut bytes.Bytes = bytes.empty()- if parsed.target.ptr != none {- next = bytes.Bytes.dup(parsed.target)- }- format.free_parsed_tag(parsed)- object.free_object(obj)- val cp4: mut ref void = current.ptr as ref void- @free(cp4)- if next.ptr == none {- return none- }- current = next- }- return none-}--fn import_blob(ctx: mut ImportCtx, oid: bytes.Bytes) option[objid.Id] = trust {- val existing = get_id(ctx.blobs_map, oid)- if existing is some id {- return some dup_id(id)- }- val id: objid.Id = lazy.blob_id(oid)- put_id(ctx.blobs_map, oid, id)- ctx.new_blobs++- return some dup_id(id)-}--fn import_tree(ctx: mut ImportCtx, oid: bytes.Bytes) option[objid.Id] = trust {- val existing = get_id(ctx.trees_map, oid)- if existing is some id {- return some dup_id(id)- }- val obj_opt = object.read_fast(ctx.git, oid)- val obj: mut object.Object = object.Object{kind: 0, body: bytes.empty(), alloc: bytes.empty()}- match obj_opt {- ok o => {- obj = o- }- err _ => {- return none- }- }- if obj.kind != object.KIND_TREE {- object.free_object(obj)- return none- }- val parsed_opt = format.parse_tree(obj.body)- val parsed: mut ref format.ParsedTree = none- match parsed_opt {- some t => {- parsed = t- }- none => {- object.free_object(obj)- return none- }- }- format.sort_raw_entries(parsed.entries)- val entries: mut list[ref tree.TreeEntry] = lists.new[ref tree.TreeEntry]()- val failed: mut bool = false- for e in parsed.entries {- val kind: u8 = format.mode_kind(e.mode)- val target: mut objid.Id = objid.id_none()- if kind == tree.KIND_SUBTREE {- val child = import_tree(ctx, e.oid)- match child {- some id => {- target = id- }- none => {- failed = true- }- }- } elif kind == tree.KIND_SUBMODULE {- val out: ref u8 = @alloc(32) as ref u8- @memset(out as ref void, 0, 32)- @memcpy(out as ref void, e.oid.ptr as ref void, 20)- target = objid.id(out)- } else {- val child2 = import_blob(ctx, e.oid)- match child2 {- some id2 => {- target = id2- }- none => {- failed = true- }- }- }- if failed {- break- }- @append(entries, tree.entry(bytes.Bytes.dup(e.name), kind, target))- }- if failed {- for te in entries {- if te.name.ptr != none {- val np: mut ref void = te.name.ptr as ref void- @free(np)- }- if te.target.ptr != none {- val ip: mut ref void = te.target.ptr as ref void- @free(ip)- }- val tp: mut ref void = te as ref void- @free(tp)- }- @listfree(entries)- format.free_parsed_tree(parsed)- object.free_object(obj)- return none- }- val body_opt = tree.encode(entries)- val body: mut bytes.Bytes = bytes.empty()- match body_opt {- ok b => {- body = b- }- err _ => {- failed = true- }- }- for te in entries {- if te.name.ptr != none {- val np2: mut ref void = te.name.ptr as ref void- @free(np2)- }- if te.target.ptr != none {- val ip2: mut ref void = te.target.ptr as ref void- @free(ip2)- }- val tp2: mut ref void = te as ref void- @free(tp2)- }- @listfree(entries)- if failed {- format.free_parsed_tree(parsed)- object.free_object(obj)- return none- }- val id: objid.Id = append_object(ctx, types.TREE, body)- put_id(ctx.trees_map, oid, id)- ctx.new_trees++- if !parsed.canonical {- val copy: bytes.Bytes = bytes.Bytes.dup(obj.body)- val rsave: mut ref ImportRawSave = @alloc(@sizeof(ImportRawSave)) as ref ImportRawSave- rsave.id = dup_id(id)- rsave.body = copy- @append(ctx.raw_saves, rsave)- }- val out2: objid.Id = dup_id(id)- format.free_parsed_tree(parsed)- object.free_object(obj)- return some out2-}--fn add_branch_target(- list: mut list[ref ImportNamedTarget],- name: bytes.Bytes,- oid: bytes.Bytes-) void = trust {- val t: mut ref ImportNamedTarget = @alloc(@sizeof(ImportNamedTarget)) as ref ImportNamedTarget- t.name = name- t.oid = oid- @append(list, t)-}--fn free_named_targets(xs: list[ref ImportNamedTarget]) void = trust {- for t in xs {- if t.oid.ptr != none {- val op: mut ref void = t.oid.ptr as ref void- @free(op)- }- val tp: mut ref void = t as ref void- @free(tp)- }- @listfree(xs)-}--fn sort_bookmarks(xs: mut list[ref view.Bookmark]) void = trust {- val n: usize = @len(xs)- val i: mut usize = 1- for i < n {- val cur = @get(xs, i)- val c: mut ref view.Bookmark = none- if cur is some v {- c = v- }- val j: mut usize = i- for j > 0 {- val prev_opt = @get(xs, j - 1)- val prev: mut ref view.Bookmark = none- if prev_opt is some v2 {- prev = v2- }- if bytes.Bytes.cmp(prev.name, c.name) <= 0 {- break- }- @set(xs, j, prev)- j--- }- @set(xs, j, c)- i++- }-}--fn sort_tags(xs: mut list[ref view.TagRef]) void = trust {- val n: usize = @len(xs)- val i: mut usize = 1- for i < n {- val cur = @get(xs, i)- val c: mut ref view.TagRef = none- if cur is some v {- c = v- }- val j: mut usize = i- for j > 0 {- val prev_opt = @get(xs, j - 1)- val prev: mut ref view.TagRef = none- if prev_opt is some v2 {- prev = v2- }- if bytes.Bytes.cmp(prev.name, c.name) <= 0 {- break- }- @set(xs, j, prev)- j--- }- @set(xs, j, c)- i++- }-}--fn set_bookmark(v: mut ref view.View, name: bytes.Bytes, id: objid.Id) void = trust {- val bi: mut usize = 0- for bi < @len(v.bookmarks) {- val bmo = @get(v.bookmarks, bi)- if bmo is some bm {- if bytes.Bytes.eql(bm.name, name) {- @listfree(bm.targets.adds)- @listfree(bm.targets.removes)- val adds: mut list[objid.Id] = lists.new[objid.Id]()- @append(adds, id)- bm.targets.adds = adds- bm.targets.removes = lists.new[objid.Id]()- return- }- }- bi++- }- val bm: mut ref view.Bookmark = @alloc(@sizeof(view.Bookmark)) as ref view.Bookmark- bm.name = bytes.Bytes.dup(name)- val adds2: mut list[objid.Id] = lists.new[objid.Id]()- @append(adds2, id)- bm.targets = view.TargetSet{adds: adds2, removes: lists.new[objid.Id]()}- @append(v.bookmarks, bm)-}--fn set_tag(v: mut ref view.View, name: bytes.Bytes, id: objid.Id) void = trust {- val ti: mut usize = 0- for ti < @len(v.tags) {- val to = @get(v.tags, ti)- if to is some t {- if bytes.Bytes.eql(t.name, name) {- t.target = id- return- }- }- ti++- }- val t: mut ref view.TagRef = @alloc(@sizeof(view.TagRef)) as ref view.TagRef- t.name = bytes.Bytes.dup(name)- t.target = id- @append(v.tags, t)-}--fn set_workspace(v: mut ref view.View, name: bytes.Bytes, id: objid.Id) void = trust {- val wi: mut usize = 0- for wi < @len(v.working_copies) {- val wo = @get(v.working_copies, wi)- if wo is some w {- if bytes.Bytes.eql(w.workspace, name) {- w.target = id- return- }- }- wi++- }- val w: mut ref view.WorkspaceRef = @alloc(@sizeof(view.WorkspaceRef)) as ref view.WorkspaceRef- w.workspace = bytes.Bytes.dup(name)- w.target = id- @append(v.working_copies, w)-}--fn clear_view_view(v: mut ref view.View) void = trust {- @listfree(v.heads)- for bm in v.bookmarks {- @listfree(bm.targets.adds)- @listfree(bm.targets.removes)- val bp: mut ref void = bm as ref void- @free(bp)- }- @listfree(v.bookmarks)- for t in v.tags {- val tp: mut ref void = t as ref void- @free(tp)- }- @listfree(v.tags)- for rr in v.remote_refs {- val rp: mut ref void = rr as ref void- @free(rp)- }- @listfree(v.remote_refs)- for w in v.working_copies {- val wp: mut ref void = w as ref void- @free(wp)- }- @listfree(v.working_copies)- @free(v as ref void)-}--fn add_unique_head(heads: mut list[objid.Id], id: objid.Id) void = trust {- for x in heads {- if objid.Id.eql(x, id) {- return- }- }- @append(heads, id)-}--fn sort_head_ids(heads: mut list[objid.Id]) void = trust {- val n: usize = @len(heads)- val i: mut usize = 1- for i < n {- val cur = @get(heads, i)- val cid: mut objid.Id = objid.id_none()- if cur is some v {- cid = v- }- val j: mut usize = i- for j > 0 {- val prev_opt = @get(heads, j - 1)- val prev: mut objid.Id = objid.id_none()- if prev_opt is some v2 {- prev = v2- }- if objid.Id.cmp(prev, cid) <= 0 {- break- }- @set(heads, j, prev)- j--- }- @set(heads, j, cid)- i++- }-}--fn free_commit_records(recs: list[ref ImportCommitRec]) void = trust {- for r in recs {- if r.body.ptr != none {- val bp: mut ref void = r.body.ptr as ref void- @free(bp)- }- if r.oid.ptr != none {- val op: mut ref void = r.oid.ptr as ref void- @free(op)- }- format.free_parsed_commit(r.parsed)- val rp: mut ref void = r as ref void- @free(rp)- }- @listfree(recs)-}--fn free_raw_saves(xs: list[ref ImportRawSave]) void = trust {- for r in xs {- if r.body.ptr != none {- val bp: mut ref void = r.body.ptr as ref void- @free(bp)- }- if r.id.ptr != none {- val ip: mut ref void = r.id.ptr as ref void- @free(ip)- }- val rp: mut ref void = r as ref void- @free(rp)- }- @listfree(xs)-}---/// Flush object batches as packs during large imports to bound peak memory.-pub fn run(repo: layout.Repo) i32 = trust {- val git_path: str.StringView = layout.git_dir(repo)- val git_opt = object.open(git_path)- val git: mut object.GitRepo = @zeroed- match git_opt {- ok g => {- git = g- }- err _ => {- files.free_path(git_path)- msg.error_prefix()- stdio.eprint("cannot open git mirror: {s}\n", {git_path})- return 1- }- }-- val commits_map_opt = gitmap.load_map(repo, str.from_cstr(c"commits"))- val trees_map_opt = gitmap.load_map(repo, str.from_cstr(c"trees"))- val blobs_map_opt = gitmap.load_map(repo, str.from_cstr(c"blobs"))- val commits_map: mut oidmap.OidMap = oidmap.new(64)- val trees_map: mut oidmap.OidMap = oidmap.new(64)- val blobs_map: mut oidmap.OidMap = oidmap.new(64)- val maps_ok: mut bool = true- match commits_map_opt {- ok m => {- commits_map = m- }- err _ => {- maps_ok = false- }- }- match trees_map_opt {- ok m2 => {- trees_map = m2- }- err _ => {- maps_ok = false- }- }- match blobs_map_opt {- ok m3 => {- blobs_map = m3- }- err _ => {- maps_ok = false- }- }- if !maps_ok {- msg.error_prefix()- stdio.eprint("corrupt git mapping table\n", {})- object.free(git)- return 1- }-- val refset: refs.RefSet = refs.read(git.git_dir)- val writer_opt = writer.open(repo)- val wref: mut ref writer.Writer = none- match writer_opt {- some w => {- wref = w- }- none => {- msg.error_prefix()- stdio.eprint("cannot create import pack\n", {})- refs.free(refset)- oidmap.free(commits_map)- oidmap.free(trees_map)- oidmap.free(blobs_map)- object.free(git)- return 1- }- }- val ctx: mut ImportCtx = ImportCtx{- git: git,- commits_map: commits_map,- trees_map: trees_map,- blobs_map: blobs_map,- raw_saves: lists.new[ref ImportRawSave](),- new_commits: 0,- new_trees: 0,- new_blobs: 0,- writer: wref- }-- val branches: mut list[ref ImportNamedTarget] = lists.new[ref ImportNamedTarget]()- val tags: mut list[ref ImportNamedTarget] = lists.new[ref ImportNamedTarget]()- val tips: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()- for b in refset.branches {- val peeled = peel_to_commit(ctx.git, b.oid)- if peeled is some c {- add_branch_target(branches, b.name, c)- @append(tips, bytes.Bytes.dup(c))- }- }- for t in refset.tags {- val peeled2 = peel_to_commit(ctx.git, t.oid)- if peeled2 is some c2 {- add_branch_target(tags, t.name, c2)- @append(tips, bytes.Bytes.dup(c2))- }- }- val head_commit: mut option[bytes.Bytes] = none- if refset.head.len > 0 {- val head_peeled = peel_to_commit(ctx.git, refset.head)- head_commit = head_peeled- if head_peeled is some h {- @append(tips, bytes.Bytes.dup(h))- }- }-- val seen: mut oidmap.OidMap = oidmap.new(64)- val records: mut list[ref ImportCommitRec] = lists.new[ref ImportCommitRec]()- val stack: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()- for t in tips {- @append(stack, t)- }- @listfree(tips)- val collect_failed: mut bool = false- for @len(stack) > 0 {- val last: usize = @len(stack) - 1- val oid: bytes.Bytes = @remove(stack, last)- if oidmap.contains(ctx.commits_map, oid) || oidmap.contains(seen, oid) {- val cp: mut ref void = oid.ptr as ref void- @free(cp)- continue- }- oidmap.put(seen, oid, bytes.empty())- val obj_opt = object.read_fast(ctx.git, oid)- val obj: mut object.Object = object.Object{- kind: 0,- body: bytes.empty(),- alloc: bytes.empty()- }- match obj_opt {- ok o => {- obj = o- }- err _ => {- collect_failed = true- val cp2: mut ref void = oid.ptr as ref void- @free(cp2)- continue- }- }- if obj.kind != object.KIND_COMMIT {- object.free_object(obj)- val cp3: mut ref void = oid.ptr as ref void- @free(cp3)- continue- }- val body: bytes.Bytes = bytes.Bytes.dup(obj.body)- object.free_object(obj)- val parsed_opt = format.parse_commit(body)- val parsed: mut ref format.ParsedCommit = none- match parsed_opt {- some p => {- parsed = p- }- none => {- collect_failed = true- val bp: mut ref void = body.ptr as ref void- @free(bp)- val cp4: mut ref void = oid.ptr as ref void- @free(cp4)- continue- }- }- val rec: mut ref ImportCommitRec = @alloc(@sizeof(ImportCommitRec)) as ref ImportCommitRec- rec.oid = oid- rec.body = body- rec.parsed = parsed- @append(records, rec)- for parent in parsed.parents {- @append(stack, bytes.Bytes.dup(parent))- }- }- @listfree(stack)- oidmap.free(seen)-- val n: usize = @len(records)- val indegree: ref u32 = @alloc(n * 4 + 1) as ref u32- @memset(indegree as ref void, 0, n * 4 + 1)- val children: mut list[list[usize]] = lists.new[list[usize]]()- val i0: mut usize = 0- for i0 < n {- @append(children, lists.new[usize]())- i0++- }- val index_map: mut oidmap.OidMap = oidmap.new(64)- val i1: mut usize = 0- for i1 < n {- val rec_opt = @get(records, i1)- if rec_opt is some rec2 {- put_usize(index_map, rec2.oid, i1)- }- i1++- }- val topo_failed: mut bool = false- val i2: mut usize = 0- for i2 < n {- val rec_opt2 = @get(records, i2)- if rec_opt2 is some rec3 {- for parent in rec3.parsed.parents {- if oidmap.contains(ctx.commits_map, parent) {- continue- }- val idx_opt = get_usize(index_map, parent)- match idx_opt {- some pidx => {- if pidx < n {- val deg_ptr: ref u32 = @ptradd(- indegree as ref void,- (i2 * 4) as i64- ) as ref u32- @store32(deg_ptr, (@load32(deg_ptr) + 1) as i32)- val child_list = @get(children, pidx)- if child_list is some cl {- @append(cl, i2)- }- }- }- none => {- topo_failed = true- }- }- }- }- i2++- }- val queue: mut list[usize] = lists.new[usize]()- val order: mut list[usize] = lists.new[usize]()- val i3: mut usize = 0- for i3 < n {- val deg_ptr2: ref u32 = @ptradd(indegree as ref void, (i3 * 4) as i64) as ref u32- if @load32(deg_ptr2) == 0 {- @append(queue, i3)- }- i3++- }- val qhead: mut usize = 0- for qhead < @len(queue) {- val cur_opt = @get(queue, qhead)- val cur: mut usize = 0- if cur_opt is some cv {- cur = cv- }- qhead++- @append(order, cur)- val child_list_opt = @get(children, cur)- if child_list_opt is some cl2 {- for child in cl2 {- val dp: ref u32 = @ptradd(indegree as ref void, (child * 4) as i64) as ref u32- val d: u32 = @load32(dp) as u32- if d > 0 {- @store32(dp, (d - 1) as i32)- if d - 1 == 0 {- @append(queue, child)- }- }- }- }- }- @listfree(queue)- if topo_failed || @len(order) != n {- msg.error_prefix()- stdio.eprint("git commit graph is incomplete or cyclic\n", {})- for cl3 in children {- @listfree(cl3)- }- @listfree(children)- @free(indegree as ref void)- oidmap.free(index_map)- free_commit_records(records)- free_named_targets(branches)- free_named_targets(tags)- if head_commit is some h2 {- val hp: mut ref void = h2.ptr as ref void- @free(hp)- }- refs.free(refset)- free_raw_saves(ctx.raw_saves)- oidmap.free(ctx.commits_map)- oidmap.free(ctx.trees_map)- oidmap.free(ctx.blobs_map)- object.free(ctx.git)- return 1- }-- val build_failed: mut bool = false- // Import trees and blobs in topological order so git delta bases are read- // before the objects that depend on them.- val ci: mut usize = 0- for ci < @len(order) {- val idx_opt = @get(order, ci)- val tree_idx: mut usize = 0- if idx_opt is some tv {- tree_idx = tv- }- val rec_opt4 = @get(records, tree_idx)- if rec_opt4 is some rec4 {- val tr = import_tree(ctx, rec4.parsed.tree)- if tr is none {- build_failed = true- break- }- if tr is some tid {- val tp: mut ref void = tid.ptr as ref void- @free(tp)- }- }- ci++- }-- val oi: mut usize = 0- for oi < @len(order) {- val idx_opt = @get(order, oi)- val idx: mut usize = 0- if idx_opt is some v {- idx = v- }- val rec_opt3 = @get(records, idx)- val rec: mut ref ImportCommitRec = none- if rec_opt3 is some v2 {- rec = v2- }- val tree_map = get_id(ctx.trees_map, rec.parsed.tree)- val root_tree: mut objid.Id = objid.id_none()- match tree_map {- some t => {- root_tree = t- }- none => {- build_failed = true- }- }- val parents: mut list[objid.Id] = lists.new[objid.Id]()- for p in rec.parsed.parents {- val pid = get_id(ctx.commits_map, p)- match pid {- some id => {- @append(parents, id)- }- none => {- build_failed = true- }- }- }- if build_failed {- @listfree(parents)- break- }- val cid: mut objid.ChangeId = objid.change_id(none)- if rec.parsed.change_id.ptr != none {- cid = objid.change_id(rec.parsed.change_id.ptr)- } else {- cid = derive_change_id(rec.oid)- }- val renames: list[ref commit.Rename] = lists.new[ref commit.Rename]()- val c: mut ref commit.Commit = @alloc(@sizeof(commit.Commit)) as ref commit.Commit- c.version = 1- c.parents = parents- c.root_tree = root_tree- c.change_id = cid- c.author = rec.parsed.author- c.committer = rec.parsed.committer- c.message = rec.parsed.message- c.renames_state = commit.RENAMES_UNKNOWN- c.renames = renames- c.extra = rec.parsed.extras- val cbody: bytes.Bytes = commit.encode(c)- val cid_out: objid.Id = append_object(ctx, types.COMMIT, cbody)- @listfree(c.parents)- @listfree(c.renames)- @free(c as ref void)- put_id(ctx.commits_map, rec.oid, cid_out)- ctx.new_commits++- val serialized: bytes.Bytes = format.serialize_commit(rec.parsed)- val is_canonical: bool = rec.parsed.canonical && bytes.Bytes.eql(serialized, rec.body)- if serialized.ptr != none {- val sp: mut ref void = serialized.ptr as ref void- @free(sp)- }- if !is_canonical {- val rsave: mut ref ImportRawSave = @alloc(@sizeof(ImportRawSave)) as ref ImportRawSave- rsave.id = dup_id(cid_out)- rsave.body = bytes.Bytes.dup(rec.body)- @append(ctx.raw_saves, rsave)- }- if cid.ptr != none && rec.parsed.change_id.ptr == none {- val cp5: mut ref void = cid.ptr as ref void- @free(cp5)- }- oi++- }- @listfree(order)- for cl4 in children {- @listfree(cl4)- }- @listfree(children)- @free(indegree as ref void)- oidmap.free(index_map)-- if build_failed {- msg.error_prefix()- stdio.eprint("referenced git object is missing\n", {})- free_commit_records(records)- free_named_targets(branches)- free_named_targets(tags)- if head_commit is some h3 {- val hp2: mut ref void = h3.ptr as ref void- @free(hp2)- }- refs.free(refset)- free_raw_saves(ctx.raw_saves)- oidmap.free(ctx.commits_map)- oidmap.free(ctx.trees_map)- oidmap.free(ctx.blobs_map)- object.free(ctx.git)- return 1- }-- if build_failed {- msg.error_prefix()- stdio.eprint("failed to import a tree or blob\n", {})- free_commit_records(records)- free_named_targets(branches)- free_named_targets(tags)- if head_commit is some h4 {- val hp3: mut ref void = h4.ptr as ref void- @free(hp3)- }- refs.free(refset)- free_raw_saves(ctx.raw_saves)- oidmap.free(ctx.commits_map)- oidmap.free(ctx.trees_map)- oidmap.free(ctx.blobs_map)- object.free(ctx.git)- return 1- }-- // Load the current view and store.- val store_handle: store.Store = store.open_all(repo)- val current = state.current_view(repo, store_handle.handles)- val v: mut ref view.View = none- val old_encoded: mut bytes.Bytes = bytes.empty()- match current {- some cv => {- v = cv- old_encoded = view.encode(v)- }- none => {- v = state.empty_view()- }- }-- for b in branches {- val id = get_id(ctx.commits_map, b.oid)- if id is some bid {- set_bookmark(v, b.name, bid)- }- }- for t in tags {- val id = get_id(ctx.commits_map, t.oid)- if id is some tid {- set_tag(v, t.name, tid)- }- }- sort_bookmarks(v.bookmarks)- sort_tags(v.tags)-- @listfree(v.heads)- val new_heads: mut list[objid.Id] = lists.new[objid.Id]()- for b in branches {- val id = get_id(ctx.commits_map, b.oid)- if id is some bid {- add_unique_head(new_heads, bid)- }- }- if @len(new_heads) == 0 {- for t in tags {- val id = get_id(ctx.commits_map, t.oid)- if id is some tid {- add_unique_head(new_heads, tid)- }- }- }- val head_id: mut objid.Id = objid.id_none()- if head_commit is some hc {- val hcid = get_id(ctx.commits_map, hc)- if hcid is some hv {- head_id = hv- }- }- if @len(new_heads) == 0 && !objid.Id.is_none(head_id) {- add_unique_head(new_heads, head_id)- }- sort_head_ids(new_heads)- v.heads = new_heads- if !objid.Id.is_none(head_id) {- set_workspace(v, bytes.bytes(c"default", 7), head_id)- } elif @len(new_heads) > 0 {- val first = @get(new_heads, 0)- if first is some fid {- set_workspace(v, bytes.bytes(c"default", 7), fid)- }- }-- val new_encoded: bytes.Bytes = view.encode(v)- val unchanged: bool = bytes.Bytes.eql(old_encoded, new_encoded)- val has_new_objects: bool = ctx.new_commits > 0 || ctx.new_trees > 0 || ctx.new_blobs > 0- if unchanged && !has_new_objects {- if old_encoded.ptr != none {- val op: mut ref void = old_encoded.ptr as ref void- @free(op)- }- if new_encoded.ptr != none {- val np: mut ref void = new_encoded.ptr as ref void- @free(np)- }- clear_view_view(v)- free_commit_records(records)- free_named_targets(branches)- free_named_targets(tags)- if head_commit is some h5 {- val hp4: mut ref void = h5.ptr as ref void- @free(hp4)- }- refs.free(refset)- free_raw_saves(ctx.raw_saves)- oidmap.free(ctx.commits_map)- oidmap.free(ctx.trees_map)- oidmap.free(ctx.blobs_map)- store.close(store_handle)- object.free(ctx.git)- msg.info_prefix()- stdio.print("already up to date\n", {})- return 0- }-- val view_id: objid.Id = append_object(ctx, types.VIEW, new_encoded)- val parent_heads: list[objid.Id] = state.heads(repo)- val op_parents: mut list[objid.Id] = lists.new[objid.Id]()- for ph in parent_heads {- @append(op_parents, ph)- }- @listfree(parent_heads)- val now: i64 = time.unix_now_millis()- val tm: prim.TimeMs = prim.TimeMs{ms: now, tz_min: 0}- val hostname: bytes.Bytes = host_from_env()- val username: bytes.Bytes = user_from_env()- val op_tags: mut list[ref prim.KeyValue] = lists.new[ref prim.KeyValue]()- val cmd_kv: mut ref prim.KeyValue = @alloc(@sizeof(prim.KeyValue)) as ref prim.KeyValue- cmd_kv.key = bytes.bytes(c"command", 7)- cmd_kv.value = bytes.bytes(c"git import", 10)- @append(op_tags, cmd_kv)- val op: mut ref operation.Operation = @alloc(@sizeof(operation.Operation)) as ref operation.Operation- op.parents = op_parents- op.view = view_id- op.start = tm- op.end = tm- op.hostname = hostname- op.username = username- op.description = bytes.bytes(c"git import", 10)- op.tags = op_tags- val op_body: bytes.Bytes = operation.encode(op)- val op_id: objid.Id = append_object(ctx, types.OPERATION, op_body)- @listfree(op.tags)- @free(op as ref void)- if hostname.ptr != none {- val hp5: mut ref void = hostname.ptr as ref void- @free(hp5)- }- if username.ptr != none {- val up: mut ref void = username.ptr as ref void- @free(up)- }-- val wrote: bool = writer.finish(ctx.writer)- if !wrote {- msg.error_prefix()- stdio.eprint("failed to write object pack\n", {})- if old_encoded.ptr != none {- val op2: mut ref void = old_encoded.ptr as ref void- @free(op2)- }- clear_view_view(v)- for ph2 in op_parents {- if ph2.ptr != none {- val pp: mut ref void = ph2.ptr as ref void- @free(pp)- }- }- @listfree(op_parents)- free_commit_records(records)- free_named_targets(branches)- free_named_targets(tags)- if head_commit is some h6 {- val hp6: mut ref void = h6.ptr as ref void- @free(hp6)- }- refs.free(refset)- free_raw_saves(ctx.raw_saves)- oidmap.free(ctx.commits_map)- oidmap.free(ctx.trees_map)- oidmap.free(ctx.blobs_map)- store.close(store_handle)- object.free(ctx.git)- return 1- }-- for rs in ctx.raw_saves {- val _ = gitmap.save_raw(repo, rs.id, rs.body)- }- val saved_commits: bool = gitmap.save_map(repo, str.from_cstr(c"commits"), ctx.commits_map)- val saved_trees: bool = gitmap.save_map(repo, str.from_cstr(c"trees"), ctx.trees_map)- val saved_blobs: bool = gitmap.save_map(repo, str.from_cstr(c"blobs"), ctx.blobs_map)- if !saved_commits || !saved_trees || !saved_blobs {- msg.error_prefix()- stdio.eprint("failed to write git mapping tables\n", {})- }- val head_ok: bool = state.write_head(repo, op_id)- if head_ok {- for ph3 in op_parents {- if !objid.Id.is_none(ph3) {- val _ = state.delete_head(repo, ph3)- }- }- }-- msg.info_prefix()- stdio.print(- "imported {d} commits, {d} trees, {d} blobs\n",- {ctx.new_commits, ctx.new_trees, ctx.new_blobs}- )-- if old_encoded.ptr != none {- val op3: mut ref void = old_encoded.ptr as ref void- @free(op3)- }- clear_view_view(v)- for ph4 in op_parents {- if ph4.ptr != none {- val pp2: mut ref void = ph4.ptr as ref void- @free(pp2)- }- }- @listfree(op_parents)- free_commit_records(records)- free_named_targets(branches)- free_named_targets(tags)- if head_commit is some h7 {- val hp7: mut ref void = h7.ptr as ref void- @free(hp7)- }- refs.free(refset)- free_raw_saves(ctx.raw_saves)- oidmap.free(ctx.commits_map)- oidmap.free(ctx.trees_map)- oidmap.free(ctx.blobs_map)- store.close(store_handle)- object.free(ctx.git)- if !head_ok {- return 1- }- return 0-}--fn host_from_env() bytes.Bytes = trust {- val h = os.env(c"HOSTNAME")- match h {- some v => {- return bytes.Bytes.dup(bytes.from_cstr(v))- }- none => {- return bytes.Bytes.dup(bytes.bytes(c"localhost", 9))- }- }-}--fn user_from_env() bytes.Bytes = trust {- val u = os.env(c"USER")- match u {- some v => {- return bytes.Bytes.dup(bytes.from_cstr(v))- }- none => {- return bytes.Bytes.dup(bytes.bytes(c"unknown", 7))- }- }-}--- a/src/src/git/lazy.sx+++ /dev/null@@ -1,53 +0,0 @@-/// Git-backed blob identifiers used by lazy imports.-///-/// A lazy blob ID is the 12-byte prefix "veins-gitoid" followed by the-/// 20-byte git object ID. Blob bodies stay in the `.veins/git` mirror until-/// they are materialized.--val bytes = use("../core/bytes.sx")-val objid = use("../object/id.sx")--pub val PREFIX_LEN: usize = 12-pub val GIT_OID_LEN: usize = 20-pub val ID_LEN: usize = 32--fn prefix() bytes.Bytes = {- return bytes.bytes(c"veins-gitoid", 12)-}--/// Build the lazy veins ID for a git blob.-pub fn blob_id(oid: bytes.Bytes) objid.Id = trust {- pre {- oid_len: oid.len == GIT_OID_LEN- }- val out: ref u8 = @alloc(ID_LEN) as ref u8- @memcpy(out as ref void, prefix().ptr as ref void, PREFIX_LEN)- @memcpy(- @ptradd(out, PREFIX_LEN as i64) as ref void,- oid.ptr as ref void,- GIT_OID_LEN- )- return objid.id(out)-}--/// True when `id` names a git-backed blob rather than a stored veins blob.-pub fn is_lazy(id: objid.Id) bool = trust {- if id.ptr == none {- return false- }- return bytes.Bytes.eql(- bytes.bytes(id.ptr, PREFIX_LEN),- prefix()- )-}--/// The git object ID carried by a lazy blob ID. The result is borrowed.-pub fn git_oid(id: objid.Id) bytes.Bytes = trust {- pre {- present: id.ptr != none- }- return bytes.bytes(- @ptradd(id.ptr, PREFIX_LEN as i64),- GIT_OID_LEN- )-}--- a/src/src/git/map.sx+++ /dev/null@@ -1,207 +0,0 @@-/// Persistent git ID mapping tables and raw-object storage.--val str = use("std/string")-val bytes = use("../core/bytes.sx")-val lists = use("../core/lists.sx")-val buf = use("../core/buf.sx")-val objid = use("../object/id.sx")-val layout = use("../store/layout.sx")-val files = use("../io/files.sx")-val native = use("../io/native.sx")-val oidmap = use("oidmap.sx")-val object = use("object.sx")--pub fn map_path(repo: layout.Repo, name: str.StringView) str.StringView = {- val dir: str.StringView = layout.git_map_dir(repo)- val p: str.StringView = files.join(dir, name)- files.free_path(dir)- return p-}--fn map_name(base: str.StringView, suffix: str.StringView) str.StringView = {- return files.with_suffix(base, suffix)-}--pub fn load_map(- repo: layout.Repo,- name: str.StringView-) result[oidmap.OidMap, object.GitError] = trust {- val base: str.StringView = layout.git_map_dir(repo)- val suffix: str.StringView = str.from_cstr(c".map")- val fname: str.StringView = files.with_suffix(name, suffix)- val path: str.StringView = files.join(base, fname)- files.free_path(base)- files.free_path(fname)- val data_opt = files.read_all(path)- files.free_path(path)- val map: mut oidmap.OidMap = oidmap.new(64)- val data: mut bytes.Bytes = bytes.empty()- match data_opt {- some d => {- data = d- }- none => {- return ok map- }- }- if data.len < 9 || !bytes.Bytes.eql(bytes.Bytes.slice(data, 0, 5), bytes.bytes(c"VMAP1", 5)) {- files.free_buffer(data)- oidmap.free(map)- return err object.GitError.Corrupt- }- val count: u32 = (bytes.Bytes.at(data, 5) as u32)- | ((bytes.Bytes.at(data, 6) as u32) << 8)- | ((bytes.Bytes.at(data, 7) as u32) << 16)- | ((bytes.Bytes.at(data, 8) as u32) << 24)- val need: u64 = 9 as u64 + (count as u64) * 52 as u64- if need != data.len as u64 {- files.free_buffer(data)- oidmap.free(map)- return err object.GitError.Corrupt- }- val i: mut usize = 0- for i < count as usize {- val off: usize = 9 + i * 52- oidmap.put(- map,- bytes.Bytes.slice(data, off, off + 20),- bytes.Bytes.slice(data, off + 20, off + 52)- )- i++- }- files.free_buffer(data)- return ok map-}--pub fn save_map(repo: layout.Repo, name: str.StringView, map: oidmap.OidMap) bool = trust {- val b: mut buf.Buf = buf.new(map.len * 52 + 16)- buf.Buf.put_raw(b, c"VMAP1", 5)- buf.Buf.put_u32_le(b, map.len as u32)- val i: mut usize = 0- for i < map.cap {- if oidmap.slot_used(map, i) {- buf.Buf.put_bytes(b, oidmap.slot_oid(map, i))- buf.Buf.put_bytes(b, oidmap.slot_value(map, i))- }- i++- }- val base: str.StringView = layout.git_map_dir(repo)- val suffix: str.StringView = str.from_cstr(c".map")- val fname: str.StringView = files.with_suffix(name, suffix)- val final: str.StringView = files.join(base, fname)- val tmpd: str.StringView = layout.tmp_dir(repo)- val tmpname: str.StringView = map_name(fname, str.from_cstr(c".tmp"))- val tmp: str.StringView = files.join(tmpd, tmpname)- val success: bool = native.write_atomic(tmp, final, tmpd, base, buf.Buf.view(b))- files.free_path(base)- files.free_path(tmpd)- files.free_path(fname)- files.free_path(final)- files.free_path(tmpname)- files.free_path(tmp)- buf.Buf.free(b)- return success-}--fn veins_hex(id: objid.Id) ref u8 = {- return objid.Id.hex(id)-}--pub fn save_raw(repo: layout.Repo, id: objid.Id, body: bytes.Bytes) bool = trust {- val hex: ref u8 = veins_hex(id)- val base: str.StringView = layout.raw_dir(repo)- val name: str.StringView = str.from_cstr(hex)- val final: str.StringView = files.join(base, name)- val tmpd: str.StringView = layout.tmp_dir(repo)- val tmpname: str.StringView = files.with_suffix(name, str.from_cstr(c".tmp"))- val tmp: str.StringView = files.join(tmpd, tmpname)- val success: bool = native.write_atomic(tmp, final, tmpd, base, body)- files.free_path(base)- files.free_path(tmpd)- files.free_path(final)- files.free_path(tmpname)- files.free_path(tmp)- @free(hex as ref void)- return success-}--pub fn has_raw(repo: layout.Repo, id: objid.Id) bool = trust {- val hex: ref u8 = veins_hex(id)- val base: str.StringView = layout.raw_dir(repo)- val name: str.StringView = str.from_cstr(hex)- val path: str.StringView = files.join(base, name)- val found: bool = files.exists_file(path)- files.free_path(base)- files.free_path(path)- @free(hex as ref void)- return found-}--pub fn load_raw(repo: layout.Repo, id: objid.Id) option[bytes.Bytes] = trust {- val hex: ref u8 = veins_hex(id)- val base: str.StringView = layout.raw_dir(repo)- val name: str.StringView = str.from_cstr(hex)- val path: str.StringView = files.join(base, name)- val data = files.read_all(path)- files.free_path(base)- files.free_path(path)- @free(hex as ref void)- return data-}--fn native_path(repo: layout.Repo) str.StringView = {- val base: str.StringView = layout.git_map_dir(repo)- val p: str.StringView = files.join(base, str.from_cstr(c"native"))- files.free_path(base)- return p-}--/// Remember that a commit was created natively so the exporter knows whether-/// to add the `veins-change-id` header.-pub fn mark_native(repo: layout.Repo, id: objid.Id) bool = trust {- val hex: ref u8 = objid.Id.hex(id)- val line: ref u8 = @fmtalloc("{s}\n", {str.from_cstr(hex)})- val p: str.StringView = native_path(repo)- val appended: bool = files.append_all(p, bytes.from_cstr(line))- files.free_path(p)- @free(hex as ref void)- @free(line as ref void)- return appended-}--pub fn load_native(repo: layout.Repo) list[objid.Id] = trust {- val out: mut list[objid.Id] = lists.new[objid.Id]()- val p: str.StringView = native_path(repo)- val data_opt = files.read_all(p)- files.free_path(p)- if data_opt is some data {- val start: mut usize = 0- val i: mut usize = 0- for i <= data.len {- if i == data.len || bytes.Bytes.at(data, i) == 10 {- val line: bytes.Bytes = bytes.Bytes.slice(data, start, i)- if line.len >= 64 {- val raw: ref u8 = @alloc(32) as ref u8- if objid.hex_decode(line.ptr, 32, raw) {- @append(out, objid.id(raw))- } else {- @free(raw as ref void)- }- }- start = i + 1- }- i++- }- files.free_buffer(data)- }- return out-}--pub fn is_native(native: list[objid.Id], id: objid.Id) bool = {- for x in native {- if objid.Id.eql(x, id) {- return true- }- }- return false-}--- a/src/src/git/mirror.sx+++ /dev/null@@ -1,158 +0,0 @@-/// Prepare the `.veins/git` mirror from an existing git repository.--val str = use("std/string")-val bytes = use("../core/bytes.sx")-val layout = use("../store/layout.sx")-val files = use("../io/files.sx")--extern (C) fn c_link(oldpath: ref u8, newpath: ref u8) i32 = "link"--fn has_git_dir(path: str.StringView) bool = {- val marker: str.StringView = files.join(path, str.from_cstr(c".git"))- val dir: bool = files.exists_dir(marker)- files.free_path(marker)- return dir-}--fn is_bare(path: str.StringView) bool = {- val head: str.StringView = files.join(path, str.from_cstr(c"HEAD"))- val objects: str.StringView = files.join(path, str.from_cstr(c"objects"))- val success: bool = files.exists_file(head) && files.exists_dir(objects)- files.free_path(head)- files.free_path(objects)- return success-}--fn gitdir_from_file(path: str.StringView) option[str.StringView] = {- val data_opt = files.read_all(path)- match data_opt {- some data => {- val prefix: bytes.Bytes = bytes.bytes(c"gitdir: ", 8)- if !bytes.Bytes.starts_with(data, prefix) {- files.free_buffer(data)- return none- }- val raw: bytes.Bytes = bytes.Bytes.slice(data, 8, data.len)- val end: mut usize = raw.len- for end > 0 && (bytes.Bytes.at(- raw,- end - 1- ) == 10 || bytes.Bytes.at(raw, end - 1) == 13) {- end--- }- val value: bytes.Bytes = bytes.Bytes.slice(raw, 0, end)- val view: str.StringView = str.view(value.ptr, value.len as i64)- val out: mut str.StringView = str.view(none, 0)- if view.len > 0 && trust @load8(view.ptr) == 47 {- out = files.with_suffix(view, str.view(none, 0))- } else {- val parent: str.StringView = files.basename(path)- val parent_path: str.StringView = str.view(path.ptr, path.len - parent.len)- out = files.join(parent_path, view)- }- files.free_buffer(data)- return some out- }- none => {- return none- }- }-}--/// Resolve a user-supplied path to the git directory it names.-pub fn resolve_source(source: str.StringView) option[str.StringView] = {- if has_git_dir(source) {- val dotgit: str.StringView = files.join(source, str.from_cstr(c".git"))- if files.exists_dir(dotgit) {- return some dotgit- }- val from_file = gitdir_from_file(dotgit)- files.free_path(dotgit)- return from_file- }- if is_bare(source) {- return some files.with_suffix(source, str.view(none, 0))- }- return none-}--fn try_link(src: str.StringView, dst: str.StringView) bool = trust {- val s: ref u8 = src.ptr- val d: ref u8 = dst.ptr- return c_link(s, d) == 0-}--fn copy_file_fallback(src: str.StringView, dst: str.StringView) bool = {- val data_opt = files.read_all(src)- match data_opt {- some data => {- val wrote: bool = files.write_all(dst, data)- files.free_buffer(data)- return wrote- }- none => {- return false- }- }-}--fn copy_tree(src: str.StringView, dst: str.StringView) bool = trust {- if !files.exists_dir(dst) {- if !files.mkdir_all(dst) {- return false- }- }- val names: list[ref u8] = files.list_dir(src)- val failed: mut bool = false- for n in names {- val name: str.StringView = str.from_cstr(n)- val s: str.StringView = files.join(src, name)- val d: str.StringView = files.join(dst, name)- if files.exists_dir(s) {- if !copy_tree(s, d) {- failed = true- }- } elif files.exists_file(s) {- if !try_link(s, d) {- if !copy_file_fallback(s, d) {- failed = true- }- }- }- files.free_path(s)- files.free_path(d)- }- files.free_names(names)- return !failed-}--/// Copy the source git directory into `.veins/git`. Existing mirrors are left-/// untouched and treated as already prepared.-pub fn prepare(repo: layout.Repo, source: str.StringView) i32 = trust {- val target: str.StringView = layout.git_dir(repo)- val head: str.StringView = files.join(target, str.from_cstr(c"HEAD"))- val already: bool = files.exists_file(head)- files.free_path(head)- if already {- files.free_path(target)- return 0- }- val src_opt = resolve_source(source)- val src: mut str.StringView = str.view(none, 0)- match src_opt {- some s => {- src = s- }- none => {- files.free_path(target)- return 2- }- }- val success: bool = copy_tree(src, target)- files.free_path(src)- files.free_path(target)- if success {- return 0- }- return 3-}--- a/src/src/git/object.sx+++ /dev/null@@ -1,1241 +0,0 @@-/// Read-only access to a git object database.-///-/// Supports loose objects, pack v2/v3 files with OFS/REF deltas, and both v1-/// and v2 pack indexes. The importer uses this instead of shelling out to git.--lib "z"-lib "crypto"--val str = use("std/string")-val bytes = use("../core/bytes.sx")-val buf = use("../core/buf.sx")-val lists = use("../core/lists.sx")-val files = use("../io/files.sx")--pub enum GitError = {- NotFound- Corrupt- Unsupported- Io- HashMismatch- OutOfMemory-}--pub fn error_name(e: GitError) str.StringView = {- match e {- GitError.NotFound => {- return "object not found"- }- GitError.Corrupt => {- return "corrupt git object data"- }- GitError.Unsupported => {- return "unsupported git format"- }- GitError.Io => {- return "git object I/O error"- }- GitError.HashMismatch => {- return "git object hash mismatch"- }- GitError.OutOfMemory => {- return "out of memory"- }- }- return "git error"-}--pub val KIND_COMMIT: u8 = 1-pub val KIND_TREE: u8 = 2-pub val KIND_BLOB: u8 = 3-pub val KIND_TAG: u8 = 4-pub val KIND_OFS_DELTA: u8 = 6-pub val KIND_REF_DELTA: u8 = 7--pub type Object = {- kind: u8- body: bytes.Bytes- alloc: bytes.Bytes-}--pub fn free_object(o: Object) void = trust {- if o.alloc.ptr != none {- val p: mut ref void = o.alloc.ptr as ref void- @free(p)- }-}--type GitCacheEntry = {- offset: mut u64- kind: mut u8- body: mut bytes.Bytes-}--type GitPack = {- path: mut str.StringView- data: mut bytes.Bytes- count: mut usize- oids: mut ref u8- offsets: mut ref u8- cache: mut list[ref GitCacheEntry]- cache_map: mut ref u32- cache_map_cap: mut usize- cache_bytes: mut usize- cache_count: mut usize-}--val CACHE_MIN: usize = 0-val CACHE_MAX_BYTES: usize = 536870912-val CACHE_MAX_ENTRIES: usize = 32768-val CACHE_MAP_CAP: usize = 262144--pub type GitRepo = {- git_dir: mut str.StringView- packs: list[ref GitPack]-}--extern (C) fn uncompress(- dest: ref u8,- dest_len: ref u64,- source: ref u8,- source_len: u64-) i32 = "uncompress"---fn be32_at(data: bytes.Bytes, off: usize) u32 = trust {- val p: ref u8 = @ptradd(data.ptr, off as i64)- return ((@load8(p) as u32) << 24) | ((@load8(@ptradd(p, 1)) as u32) << 16)- | ((@load8(@ptradd(p, 2)) as u32) << 8) | (@load8(@ptradd(p, 3)) as u32)-}--fn be64_at(data: bytes.Bytes, off: usize) u64 = trust {- val p: ref u8 = @ptradd(data.ptr, off as i64)- val hi: u64 = ((@load8(p) as u64) << 56) | ((@load8(@ptradd(p, 1)) as u64) << 48)- | ((@load8(@ptradd(p, 2)) as u64) << 40) | ((@load8(@ptradd(p, 3)) as u64) << 32)- val lo: u64 = ((@load8(@ptradd(p, 4)) as u64) << 24) | ((@load8(@ptradd(p, 5)) as u64) << 16)- | ((@load8(@ptradd(p, 6)) as u64) << 8) | (@load8(@ptradd(p, 7)) as u64)- return hi | lo-}--extern (C) fn SHA1(data: ref u8, len: usize, out: ref u8) ref u8 = "SHA1"--fn sha1_of(data: bytes.Bytes) option[bytes.Bytes] = trust {- val out: ref u8 = @alloc(20) as ref u8- val r: ref u8 = SHA1(data.ptr, data.len, out)- if r == none {- @free(out as ref void)- return none- }- return some bytes.bytes(out, 20)-}--pub fn free_digest(d: bytes.Bytes) void = trust {- if d.ptr != none {- val p: mut ref void = d.ptr as ref void- @free(p)- }-}--fn put_decimal(b: mut buf.Buf, v: u64) void = trust {- if v == 0 {- buf.Buf.put_u8(b, 48)- return- }- val tmp: ref u8 = @alloc(24) as ref u8- val n: mut usize = 0- val x: mut u64 = v- for x > 0 {- @store8(@ptradd(tmp, n as i64), (48 + (x % 10)) as u8)- x = x / 10- n++- }- val i: mut usize = n- for i > 0 {- i--- buf.Buf.put_u8(b, @load8(@ptradd(tmp, i as i64)))- }- @free(tmp as ref void)-}--fn kind_name(kind: u8) str.StringView = {- if kind == KIND_COMMIT {- return "commit"- }- if kind == KIND_TREE {- return "tree"- }- if kind == KIND_BLOB {- return "blob"- }- if kind == KIND_TAG {- return "tag"- }- return "unknown"-}--fn kind_from_name(name: bytes.Bytes) u8 = {- if bytes.Bytes.eql(name, bytes.bytes(c"commit", 6)) {- return KIND_COMMIT- }- if bytes.Bytes.eql(name, bytes.bytes(c"tree", 4)) {- return KIND_TREE- }- if bytes.Bytes.eql(name, bytes.bytes(c"blob", 4)) {- return KIND_BLOB- }- if bytes.Bytes.eql(name, bytes.bytes(c"tag", 3)) {- return KIND_TAG- }- return 0-}--/// Git object hash: SHA-1("<kind> <length>\0" || body).-pub fn object_hash(kind: u8, body: bytes.Bytes) option[bytes.Bytes] = trust {- val b: mut buf.Buf = buf.new(body.len + 32)- buf.Buf.put_bytes(b, bytes.from_cstr(kind_name(kind).ptr))- buf.Buf.put_u8(b, 32)- put_decimal(b, body.len as u64)- buf.Buf.put_u8(b, 0)- buf.Buf.put_bytes(b, body)- val out = sha1_of(buf.Buf.view(b))- buf.Buf.free(b)- return out-}--fn verify_hash(oid: bytes.Bytes, kind: u8, body: bytes.Bytes) bool = trust {- val got = object_hash(kind, body)- match got {- some h => {- val same: bool = bytes.Bytes.eql(h, oid)- free_digest(h)- return same- }- none => {- return false- }- }-}--fn inflate_exact(input: bytes.Bytes, expected: usize) option[bytes.Bytes] = trust {- val cap: usize = expected + 1- val dst: ref u8 = @alloc(cap) as ref u8- val dest_len: ref u64 = @alloc(8) as ref u64- @store64(dest_len as ref void, expected as u64)- val rc: i32 = uncompress(- dst,- dest_len,- input.ptr,- input.len as u64- )- val got: u64 = @load64(dest_len as ref void) as u64- @free(dest_len as ref void)- if rc != 0 || got != expected as u64 {- @free(dst as ref void)- return none- }- return some bytes.bytes(dst, expected)-}--fn inflate_unknown(input: bytes.Bytes) option[bytes.Bytes] = trust {- val base: mut usize = input.len * 3 + 4096- for base <= 1073741824 {- val dst: ref u8 = @alloc(base + 1) as ref u8- val dest_len: ref u64 = @alloc(8) as ref u64- @store64(dest_len as ref void, base as u64)- val rc: i32 = uncompress(dst, dest_len, input.ptr, input.len as u64)- val got: u64 = @load64(dest_len as ref void) as u64- @free(dest_len as ref void)- if rc == 0 {- return some bytes.bytes(dst, got as usize)- }- @free(dst as ref void)- if rc != -5 {- return none- }- base = base * 2- }- return none-}--fn hex_digit(n: u8) u8 = {- if n < 10 {- return (48 + n) as u8- }- return (87 + n) as u8-}--fn oid_hex(oid: bytes.Bytes) ref u8 = trust {- val out: ref u8 = @alloc(41) as ref u8- val i: mut usize = 0- for i < 20 {- val v: u8 = bytes.Bytes.at(oid, i)- @store8(@ptradd(out, (i * 2) as i64), hex_digit(v >> 4))- @store8(@ptradd(out, (i * 2 + 1) as i64), hex_digit(v & 15))- i++- }- @store8(@ptradd(out, 40), 0)- return out-}--type GitVarint = {- value: u64- next: usize-}--fn read_be_varint(data: bytes.Bytes, start: usize) option[GitVarint] = {- if start >= data.len {- return none- }- val c0: u8 = bytes.Bytes.at(data, start)- val size: mut u64 = (c0 & 0x0f) as u64- val shift: mut u64 = 4- val i: mut usize = start + 1- val more: mut bool = (c0 & 0x80) != 0- for more {- if i >= data.len {- return none- }- val c: u8 = bytes.Bytes.at(data, i)- i++- size = size | (((c & 0x7f) as u64) << shift)- shift = shift + 7- more = (c & 0x80) != 0- }- return some GitVarint{value: size, next: i}-}--fn read_delta_varint(data: bytes.Bytes, start: usize) option[GitVarint] = {- val v: mut u64 = 0- val shift: mut u64 = 0- val i: mut usize = start- for {- if i >= data.len || shift > 63 {- return none- }- val c: u8 = bytes.Bytes.at(data, i)- i++- v = v | (((c & 0x7f) as u64) << shift)- shift = shift + 7- if (c & 0x80) == 0 {- return some GitVarint{value: v, next: i}- }- }- return none-}--fn apply_delta(base: bytes.Bytes, delta: bytes.Bytes) option[bytes.Bytes] = trust {- val src_opt = read_delta_varint(delta, 0)- val src_size: mut u64 = 0- val p: mut usize = 0- match src_opt {- some r => {- src_size = r.value- p = r.next- }- none => {- return none- }- }- if src_size != base.len as u64 {- return none- }- val dst_opt = read_delta_varint(delta, p)- val dst_size: mut u64 = 0- match dst_opt {- some r => {- dst_size = r.value- p = r.next- }- none => {- return none- }- }- if dst_size > 2147483648 {- return none- }- val cap: usize = dst_size as usize- val out: ref u8 = @alloc(cap + 1) as ref u8- val written: mut usize = 0- for p < delta.len {- val op: u8 = bytes.Bytes.at(delta, p)- p++- if (op & 0x80) != 0 {- val off: mut u64 = 0- val size: mut u64 = 0- if (op & 0x01) != 0 {- if p >= delta.len {- @free(out as ref void)- return none- }- off = off | (bytes.Bytes.at(delta, p) as u64)- p++- }- if (op & 0x02) != 0 {- if p >= delta.len {- @free(out as ref void)- return none- }- off = off | ((bytes.Bytes.at(delta, p) as u64) << 8)- p++- }- if (op & 0x04) != 0 {- if p >= delta.len {- @free(out as ref void)- return none- }- off = off | ((bytes.Bytes.at(delta, p) as u64) << 16)- p++- }- if (op & 0x08) != 0 {- if p >= delta.len {- @free(out as ref void)- return none- }- off = off | ((bytes.Bytes.at(delta, p) as u64) << 24)- p++- }- if (op & 0x10) != 0 {- if p >= delta.len {- @free(out as ref void)- return none- }- size = size | (bytes.Bytes.at(delta, p) as u64)- p++- }- if (op & 0x20) != 0 {- if p >= delta.len {- @free(out as ref void)- return none- }- size = size | ((bytes.Bytes.at(delta, p) as u64) << 8)- p++- }- if (op & 0x40) != 0 {- if p >= delta.len {- @free(out as ref void)- return none- }- size = size | ((bytes.Bytes.at(delta, p) as u64) << 16)- p++- }- if size == 0 {- size = 65536- }- if off > base.len as u64 || size > (base.len as u64) - off {- @free(out as ref void)- return none- }- if size > (cap as u64) - (written as u64) {- @free(out as ref void)- return none- }- if size > 0 {- @memcpy(- @ptradd(out, written as i64) as ref void,- @ptradd(base.ptr, off as i64) as ref void,- size as usize- )- }- written = written + size as usize- } else {- if op == 0 {- @free(out as ref void)- return none- }- val n: usize = op as usize- if p + n > delta.len || n > cap - written {- @free(out as ref void)- return none- }- @memcpy(- @ptradd(out, written as i64) as ref void,- @ptradd(delta.ptr, p as i64) as ref void,- n- )- p = p + n- written = written + n- }- }- if written != cap {- @free(out as ref void)- return none- }- return some bytes.bytes(out, cap)-}--fn find_oid(pack: ref GitPack, oid: bytes.Bytes) option[usize] = trust {- pre {- oid_len: oid.len == 20- }- val lo: mut usize = 0- val hi: mut usize = pack.count- for lo < hi {- val mid: usize = lo + (hi - lo) / 2- val cur: bytes.Bytes = bytes.bytes(@ptradd(pack.oids, (mid * 20) as i64), 20)- val c: i64 = bytes.Bytes.cmp(cur, oid)- if c == 0 {- return some mid- }- if c < 0 {- lo = mid + 1- } else {- hi = mid- }- }- return none-}--fn offset_at(pack: ref GitPack, i: usize) u64 = trust {- return @load64(@ptradd(pack.offsets, (i * 8) as i64)) as u64-}--fn cache_hash(offset: u64) usize = {- val h: u64 = offset * 11400714819323198485- return (h >> 32) as usize-}--fn cache_slot(pack: ref GitPack, offset: u64) i64 = trust {- if pack.cache_map_cap == 0 {- return -1- }- val mask: usize = pack.cache_map_cap - 1- val start: usize = cache_hash(offset) & mask- val idx: mut usize = start- for {- val slot: ref u32 = @ptradd(pack.cache_map as ref void, (idx * 4) as i64) as ref u32- val v: u32 = @load32(slot) as u32- if v == 0 {- return -1- }- if v != 4294967295 {- val ei: usize = (v - 1) as usize- val o = @get(pack.cache, ei)- if o is some e {- if e.body.ptr != none && e.offset == offset {- return ei as i64- }- }- }- idx = (idx + 1) & mask- if idx == start {- return -1- }- }- return -1-}--fn cache_map_put(pack: ref GitPack, offset: u64, entry: usize) void = trust {- if pack.cache_map_cap == 0 {- return- }- val mask: usize = pack.cache_map_cap - 1- val start: usize = cache_hash(offset) & mask- val idx: mut usize = start- val tomb: mut i64 = -1- for {- val slot: ref u32 = @ptradd(pack.cache_map as ref void, (idx * 4) as i64) as ref u32- val v: u32 = @load32(slot) as u32- if v == 0 {- val at: mut usize = idx- if tomb >= 0 {- at = tomb as usize- }- val at_slot: ref u32 = @ptradd(pack.cache_map as ref void, (at * 4) as i64) as ref u32- @store32(at_slot as ref void, (entry + 1) as i32)- return- }- if v == 4294967295 && tomb < 0 {- tomb = idx as i64- }- idx = (idx + 1) & mask- if idx == start {- if tomb >= 0 {- val tslot: ref u32 = @ptradd(- pack.cache_map as ref void,- ((tomb as usize) * 4) as i64- ) as ref u32- @store32(tslot as ref void, (entry + 1) as i32)- }- return- }- }-}--fn cache_map_remove(pack: ref GitPack, offset: u64) void = trust {- if pack.cache_map_cap == 0 {- return- }- val mask: usize = pack.cache_map_cap - 1- val start: usize = cache_hash(offset) & mask- val idx: mut usize = start- for {- val slot: ref u32 = @ptradd(pack.cache_map as ref void, (idx * 4) as i64) as ref u32- val v: u32 = @load32(slot) as u32- if v == 0 {- return- }- if v != 4294967295 {- val ei: usize = (v - 1) as usize- val o = @get(pack.cache, ei)- if o is some e {- if e.offset == offset {- @store32(slot as ref void, -1)- return- }- }- }- idx = (idx + 1) & mask- if idx == start {- return- }- }-}--fn cache_lookup(pack: ref GitPack, offset: u64) option[Object] = trust {- val slot: i64 = cache_slot(pack, offset)- if slot < 0 {- return none- }- val o = @get(pack.cache, slot as usize)- if o is some e {- return some Object{kind: e.kind, body: e.body, alloc: bytes.empty()}- }- return none-}--fn cache_evict_one(pack: mut ref GitPack) void = trust {- val victim: mut i64 = -1- val oldest_off: mut u64 = 18446744073709551615- val i: mut usize = 0- for i < @len(pack.cache) {- val o = @get(pack.cache, i)- if o is some e {- if e.body.ptr != none && e.offset < oldest_off {- oldest_off = e.offset- victim = i as i64- }- }- i++- }- if victim < 0 {- return- }- val vo = @get(pack.cache, victim as usize)- if vo is some e2 {- if e2.body.ptr != none {- pack.cache_bytes = pack.cache_bytes - e2.body.len- pack.cache_count = pack.cache_count - 1- cache_map_remove(pack, e2.offset)- val bp: mut ref void = e2.body.ptr as ref void- @free(bp)- e2.body = bytes.empty()- }- }-}--fn cache_store(pack: mut ref GitPack, offset: u64, kind: u8, body: bytes.Bytes) bool = trust {- if body.len < CACHE_MIN || body.len > CACHE_MAX_BYTES {- return false- }- if cache_slot(pack, offset) >= 0 {- return false- }- for pack.cache_count > 0 {- if pack.cache_bytes + body.len <= CACHE_MAX_BYTES- && pack.cache_count < CACHE_MAX_ENTRIES {- break- }- cache_evict_one(pack)- }- if pack.cache_bytes + body.len > CACHE_MAX_BYTES {- return false- }- val e: mut ref GitCacheEntry = @alloc(@sizeof(GitCacheEntry)) as ref GitCacheEntry- e.offset = offset- e.kind = kind- e.body = body- val slot: mut i64 = -1- val i: mut usize = 0- for i < @len(pack.cache) {- val o = @get(pack.cache, i)- if o is some x {- if x.body.ptr == none {- slot = i as i64- break- }- }- i++- }- if slot >= 0 {- @set(pack.cache, slot as usize, e)- } else {- @append(pack.cache, e)- }- pack.cache_bytes = pack.cache_bytes + body.len- pack.cache_count = pack.cache_count + 1- val map_slot: usize = @len(pack.cache) - 1- if slot >= 0 {- cache_map_put(pack, offset, slot as usize)- } else {- cache_map_put(pack, offset, map_slot)- }- return true-}--fn cache_free(pack: ref GitPack) void = trust {- if pack.cache_map != none {- @free(pack.cache_map as ref void)- }- for e in pack.cache {- if e.body.ptr != none {- val bp: mut ref void = e.body.ptr as ref void- @free(bp)- }- val ep: mut ref void = e as ref void- @free(ep)- }- @listfree(pack.cache)-}--fn read_at(- repo: GitRepo,- pack: mut ref GitPack,- start: u64,- verify: bool,- use_cache: bool-) result[Object, GitError] = trust {- if use_cache {- val cached = cache_lookup(pack, start)- if cached is some c {- return ok c- }- }- val data: bytes.Bytes = pack.data- val pos: mut usize = start as usize- if pos >= data.len {- return err GitError.Corrupt- }- val c0: u8 = bytes.Bytes.at(data, pos)- val kind: u8 = (c0 >> 4) & 7- val size_opt = read_be_varint(data, start as usize)- val size: mut u64 = 0- match size_opt {- some v => {- size = v.value- pos = v.next- }- none => {- return err GitError.Corrupt- }- }- if size > 2147483648 {- return err GitError.Unsupported- }-- val base_oid: mut bytes.Bytes = bytes.empty()- val base_off: mut u64 = 0- val has_base_off: mut bool = false- if kind == KIND_OFS_DELTA {- if pos >= data.len {- return err GitError.Corrupt- }- val c: u8 = bytes.Bytes.at(data, pos)- pos++- val acc: mut u64 = (c & 0x7f) as u64- val more: mut bool = (c & 0x80) != 0- for more {- if pos >= data.len {- return err GitError.Corrupt- }- val c2: u8 = bytes.Bytes.at(data, pos)- pos++- acc = ((acc + 1) << 7) | ((c2 & 0x7f) as u64)- more = (c2 & 0x80) != 0- }- has_base_off = true- base_off = start - acc- } elif kind == KIND_REF_DELTA {- if pos + 20 > data.len {- return err GitError.Corrupt- }- base_oid = bytes.Bytes.slice(data, pos, pos + 20)- pos = pos + 20- }-- val comp: bytes.Bytes = bytes.Bytes.slice(data, pos, data.len)- val inflated_opt = inflate_exact(comp, size as usize)- val inflated: mut bytes.Bytes = bytes.empty()- match inflated_opt {- some x => {- inflated = x- }- none => {- return err GitError.Corrupt- }- }-- if kind >= KIND_COMMIT && kind <= KIND_TAG {- if use_cache && cache_store(pack, start, kind, inflated) {- return ok Object{kind: kind, body: inflated, alloc: bytes.empty()}- }- return ok Object{kind: kind, body: inflated, alloc: inflated}- }- if kind != KIND_OFS_DELTA && kind != KIND_REF_DELTA {- @free(inflated.ptr as ref void)- return err GitError.Corrupt- }-- val base: mut Object = Object{kind: 0, body: bytes.empty(), alloc: bytes.empty()}- if has_base_off {- if base_off >= start {- @free(inflated.ptr as ref void)- return err GitError.Corrupt- }- val br = read_at(repo, pack, base_off, verify, use_cache)- match br {- ok b => {- base = b- }- err e => {- @free(inflated.ptr as ref void)- return err e- }- }- } else {- val br2 = read_impl(repo, base_oid, verify, use_cache)- match br2 {- ok b => {- base = b- }- err e => {- @free(inflated.ptr as ref void)- return err e- }- }- }-- val merged_opt = apply_delta(base.body, inflated)- val merged: mut bytes.Bytes = bytes.empty()- match merged_opt {- some x => {- merged = x- }- none => {- free_object(base)- @free(inflated.ptr as ref void)- return err GitError.Corrupt- }- }- val base_kind: u8 = base.kind- free_object(base)- @free(inflated.ptr as ref void)- if use_cache && cache_store(pack, start, base_kind, merged) {- return ok Object{kind: base_kind, body: merged, alloc: bytes.empty()}- }- return ok Object{kind: base_kind, body: merged, alloc: merged}-}--fn read_loose(repo: GitRepo, oid: bytes.Bytes, verify: bool) option[Object] = trust {- val hex: ref u8 = oid_hex(oid)- val objroot: str.StringView = files.join(repo.git_dir, str.from_cstr(c"objects"))- val dirname: str.StringView = str.view(hex, 2)- val rest: str.StringView = str.view(@ptradd(hex, 2), 38)- val dir: str.StringView = files.join(objroot, dirname)- val path: str.StringView = files.join(dir, rest)- files.free_path(objroot)- files.free_path(dir)- @free(hex as ref void)- val exists: bool = files.exists_file(path)- if !exists {- files.free_path(path)- return none- }- val data_opt = files.read_all(path)- files.free_path(path)- val compressed: mut bytes.Bytes = bytes.empty()- match data_opt {- some d => {- compressed = d- }- none => {- return none- }- }- val inflated_opt = inflate_unknown(compressed)- files.free_buffer(compressed)- val inflated: mut bytes.Bytes = bytes.empty()- match inflated_opt {- some x => {- inflated = x- }- none => {- return none- }- }- val space: mut usize = 0- for space < inflated.len && bytes.Bytes.at(inflated, space) != 32 {- space++- }- val nul: mut usize = space- for nul < inflated.len && bytes.Bytes.at(inflated, nul) != 0 {- nul++- }- if space == 0 || nul >= inflated.len {- @free(inflated.ptr as ref void)- return none- }- val kind: u8 = kind_from_name(bytes.Bytes.slice(inflated, 0, space))- if kind == 0 {- @free(inflated.ptr as ref void)- return none- }- val size_text: bytes.Bytes = bytes.Bytes.slice(inflated, space + 1, nul)- val declared: mut u64 = 0- val i: mut usize = 0- for i < size_text.len {- val c: u8 = bytes.Bytes.at(size_text, i)- if c < 48 || c > 57 {- @free(inflated.ptr as ref void)- return none- }- declared = declared * 10 + (c - 48) as u64- i++- }- val body: bytes.Bytes = bytes.Bytes.slice(inflated, nul + 1, inflated.len)- if body.len as u64 != declared {- @free(inflated.ptr as ref void)- return none- }- val o = Object{kind: kind, body: body, alloc: inflated}- if verify && !verify_hash(oid, kind, body) {- free_object(o)- return none- }- return some o-}--fn read_impl(- repo: GitRepo,- oid: bytes.Bytes,- verify: bool,- use_cache: bool-) result[Object, GitError] = trust {- pre {- oid_len: oid.len == 20- }- val i: mut usize = 0- for i < @len(repo.packs) {- val p: mut ref GitPack = pack_at(repo.packs, i)- val found = find_oid(p, oid)- if found is some idx {- val r = read_at(repo, p, offset_at(p, idx), verify, use_cache)- match r {- ok o => {- if verify && !verify_hash(oid, o.kind, o.body) {- free_object(o)- return err GitError.HashMismatch- }- return ok o- }- err e => {- return err e- }- }- }- i++- }- val loose = read_loose(repo, oid, verify)- if loose is some o2 {- return ok o2- }- return err GitError.NotFound-}--pub fn read(repo: GitRepo, oid: bytes.Bytes) result[Object, GitError] = trust {- return read_impl(repo, oid, true, false)-}--/// Read an object without recomputing its hash. The pack trailer and index are-/// already verified when the pack is opened, so this is safe for local import.-pub fn read_fast(repo: GitRepo, oid: bytes.Bytes) result[Object, GitError] = trust {- return read_impl(repo, oid, false, true)-}--fn pack_at(packs: list[ref GitPack], i: usize) ref GitPack = {- val o = @get(packs, i)- if o is some p {- return p- }- assert false- return none-}--fn parse_idx(- data: bytes.Bytes,- pack_count: usize,- pack_trailer: bytes.Bytes-) result[ref GitPack, GitError] = trust {- if data.len < 40 {- return err GitError.Corrupt- }- val trailer_off: usize = data.len - 20- val check_opt = sha1_of(bytes.Bytes.slice(data, 0, trailer_off))- val check: mut bytes.Bytes = bytes.empty()- match check_opt {- some d => {- check = d- }- none => {- return err GitError.OutOfMemory- }- }- val check_ok: bool = bytes.Bytes.eql(check, bytes.Bytes.slice(data, trailer_off, data.len))- free_digest(check)- if !check_ok {- return err GitError.Corrupt- }- if !bytes.Bytes.eql(- bytes.Bytes.slice(data, data.len - 40, data.len - 20),- pack_trailer- ) {- return err GitError.Corrupt- }-- val is_v2: bool = data.len >= 8- && bytes.Bytes.at(data, 0) == 255- && bytes.Bytes.at(data, 1) == 116- && bytes.Bytes.at(data, 2) == 79- && bytes.Bytes.at(data, 3) == 99- val fanout_off: mut usize = 0- if is_v2 {- fanout_off = 8- }- if is_v2 {- val version: u32 = be32_at(data, 4)- if version != 2 {- return err GitError.Unsupported- }- }- if data.len < fanout_off + 1024 + 40 {- return err GitError.Corrupt- }- val n: usize = be32_at(data, fanout_off + 255 * 4) as usize- if n != pack_count {- return err GitError.Corrupt- }- val oids: ref u8 = @alloc(n * 20 + 1) as ref u8- val offsets: ref u8 = @alloc(n * 8 + 1) as ref u8- if is_v2 {- val names_off: usize = fanout_off + 1024- val crcs_off: usize = names_off + n * 20- val offs_off: usize = crcs_off + n * 4- val large_off: usize = offs_off + n * 4- if large_off + 40 > data.len {- @free(oids as ref void)- @free(offsets as ref void)- return err GitError.Corrupt- }- val large_bytes: usize = data.len - 40 - large_off- if large_bytes % 8 != 0 {- @free(oids as ref void)- @free(offsets as ref void)- return err GitError.Corrupt- }- val i: mut usize = 0- for i < n {- @memcpy(- @ptradd(oids, (i * 20) as i64) as ref void,- @ptradd(data.ptr, (names_off + i * 20) as i64) as ref void,- 20- )- val raw_off: u32 = be32_at(data, offs_off + i * 4)- val resolved: mut u64 = raw_off as u64- if (raw_off & 2147483648) != 0 {- val idx: usize = (raw_off & 2147483647) as usize- if idx * 8 + 8 > large_bytes {- @free(oids as ref void)- @free(offsets as ref void)- return err GitError.Corrupt- }- resolved = be64_at(data, large_off + idx * 8)- }- @store64(@ptradd(offsets, (i * 8) as i64), resolved as i64)- i++- }- } else {- val records_off: usize = 1024- if records_off + n * 24 + 40 > data.len {- @free(oids as ref void)- @free(offsets as ref void)- return err GitError.Corrupt- }- val j: mut usize = 0- for j < n {- val rec: usize = records_off + j * 24- val off: u64 = be32_at(data, rec) as u64- @store64(@ptradd(offsets, (j * 8) as i64), off as i64)- @memcpy(- @ptradd(oids, (j * 20) as i64) as ref void,- @ptradd(data.ptr, (rec + 4) as i64) as ref void,- 20- )- j++- }- }-- val p: mut ref GitPack = @alloc(@sizeof(GitPack)) as ref GitPack- p.path = str.view(none, 0)- p.data = bytes.empty()- p.count = n- p.oids = oids- p.offsets = offsets- p.cache = lists.new[ref GitCacheEntry]()- p.cache_map_cap = CACHE_MAP_CAP- p.cache_map = @alloc(CACHE_MAP_CAP * 4) as ref u32- @memset(p.cache_map as ref void, 0, CACHE_MAP_CAP * 4)- p.cache_bytes = 0- p.cache_count = 0- return ok p-}--fn open_pack(- pack_path: str.StringView,- idx_path: str.StringView-) result[ref GitPack, GitError] = trust {- val pdata_opt = files.read_all(pack_path)- val pdata: mut bytes.Bytes = bytes.empty()- match pdata_opt {- some d => {- pdata = d- }- none => {- return err GitError.Io- }- }- if pdata.len < 32 || !bytes.Bytes.eql(bytes.Bytes.slice(pdata, 0, 4), bytes.bytes(c"PACK", 4)) {- files.free_buffer(pdata)- return err GitError.Corrupt- }- val version: u32 = be32_at(pdata, 4)- if version != 2 && version != 3 {- files.free_buffer(pdata)- return err GitError.Unsupported- }- val count: usize = be32_at(pdata, 8) as usize- val trailer_off: usize = pdata.len - 20- val pack_trailer: bytes.Bytes = bytes.Bytes.slice(pdata, trailer_off, pdata.len)- val hash_opt = sha1_of(bytes.Bytes.slice(pdata, 0, trailer_off))- val hash: mut bytes.Bytes = bytes.empty()- match hash_opt {- some d => {- hash = d- }- none => {- files.free_buffer(pdata)- return err GitError.OutOfMemory- }- }- val hash_ok: bool = bytes.Bytes.eql(hash, pack_trailer)- free_digest(hash)- if !hash_ok {- files.free_buffer(pdata)- return err GitError.Corrupt- }-- val idata_opt = files.read_all(idx_path)- val idata: mut bytes.Bytes = bytes.empty()- match idata_opt {- some d => {- idata = d- }- none => {- files.free_buffer(pdata)- return err GitError.Io- }- }- val pr = parse_idx(idata, count, pack_trailer)- files.free_buffer(idata)- val p: mut ref GitPack = none- match pr {- ok x => {- p = x- }- err e => {- files.free_buffer(pdata)- return err e- }- }- p.path = pack_path- p.data = pdata- return ok p-}--pub fn open(git_dir: str.StringView) result[GitRepo, GitError] = trust {- val packs: mut list[ref GitPack] = lists.new[ref GitPack]()- val pack_dir: str.StringView = files.join(git_dir, str.from_cstr(c"objects/pack"))- if files.exists_dir(pack_dir) {- val names: list[ref u8] = files.list_dir(pack_dir)- for n in names {- if files.name_ends_with(n, c".idx") {- val iv: str.StringView = str.from_cstr(n)- val base: str.StringView = str.view(iv.ptr, iv.len - 4)- val pack_name: str.StringView = files.with_suffix(base, ".pack")- val pack_path: str.StringView = files.join(pack_dir, pack_name)- val idx_path: str.StringView = files.join(pack_dir, iv)- files.free_path(pack_name)- if files.exists_file(pack_path) {- val r = open_pack(pack_path, idx_path)- match r {- ok p => {- @append(packs, p)- files.free_path(idx_path)- }- err e => {- files.free_path(pack_path)- files.free_path(idx_path)- files.free_names(names)- files.free_path(pack_dir)- for x in packs {- free_pack(x)- }- @listfree(packs)- return err e- }- }- } else {- files.free_path(pack_path)- files.free_path(idx_path)- }- }- }- files.free_names(names)- }- files.free_path(pack_dir)- return ok GitRepo{git_dir: git_dir, packs: packs}-}--pub fn free_pack(p: ref GitPack) void = trust {- files.free_buffer(p.data)- cache_free(p)- if p.oids != none {- @free(p.oids as ref void)- }- if p.offsets != none {- @free(p.offsets as ref void)- }- if p.path.ptr != none {- files.free_path(p.path)- }- @free(p as ref void)-}--pub fn free(repo: mut GitRepo) void = trust {- for p in repo.packs {- free_pack(p)- }- @listfree(repo.packs)- if repo.git_dir.ptr != none {- files.free_path(repo.git_dir)- }- repo.git_dir = str.view(none, 0)-}--- a/src/src/git/oidmap.sx+++ /dev/null@@ -1,198 +0,0 @@-/// A small open-addressed map keyed by 20-byte git object IDs.-///-/// Slots store the key, a 32-byte payload, and a used flag. This is used for-/// reachability sets and for the in-memory git-to-veins ID maps during import.--val bytes = use("../core/bytes.sx")--pub val OID_LEN: usize = 20-pub val VALUE_LEN: usize = 32-pub val SLOT_LEN: usize = 56--pub type OidMap = {- slots: mut ref u8- cap: mut usize- len: mut usize-}--fn round_cap(n: usize) usize = trust {- val c: mut usize = 16- for c < n {- c = c * 2- }- return c-}--fn oid_ptr(map: OidMap, i: usize) ref u8 = trust {- return @ptradd(map.slots, (i * SLOT_LEN + 1) as i64)-}--fn value_ptr(map: OidMap, i: usize) ref u8 = trust {- return @ptradd(map.slots, (i * SLOT_LEN + 1 + OID_LEN) as i64)-}--fn used_at(map: OidMap, i: usize) bool = trust {- return @load8(@ptradd(map.slots, (i * SLOT_LEN) as i64)) != 0-}--fn set_used(map: OidMap, i: usize) void = trust {- @store8(@ptradd(map.slots, (i * SLOT_LEN) as i64), 1)-}--fn hash_oid(oid: bytes.Bytes) u64 = trust {- val h: mut u64 = 1469598103934665603- val k: mut usize = 0- for k < OID_LEN {- h = (h ^ (bytes.Bytes.at(oid, k) as u64)) * 1099511628211- k++- }- return h-}--fn slot_eql(map: OidMap, i: usize, oid: bytes.Bytes) bool = trust {- return bytes.Bytes.eql(bytes.bytes(oid_ptr(map, i), OID_LEN), oid)-}--fn copy_key(map: OidMap, i: usize, oid: bytes.Bytes) void = trust {- @memcpy(oid_ptr(map, i) as ref void, oid.ptr as ref void, OID_LEN)-}--fn copy_value(map: OidMap, i: usize, value: bytes.Bytes) void = trust {- @memset(value_ptr(map, i) as ref void, 0, VALUE_LEN)- if value.len > 0 {- val n: mut usize = value.len- if n > VALUE_LEN {- n = VALUE_LEN- }- @memcpy(value_ptr(map, i) as ref void, value.ptr as ref void, n)- }-}--pub fn new(initial: usize) OidMap = trust {- val cap: usize = round_cap(initial)- val p: ref u8 = @alloc(cap * SLOT_LEN) as ref u8- @memset(p as ref void, 0, cap * SLOT_LEN)- return OidMap{slots: p, cap: cap, len: 0}-}--pub fn free(map: mut OidMap) void = trust {- if map.slots != none {- @free(map.slots as ref void)- }- map.slots = none- map.cap = 0- map.len = 0-}--pub fn count(map: OidMap) usize = trust {- return map.len-}--fn insert_slot(map: mut OidMap, oid: bytes.Bytes, value: bytes.Bytes) void = trust {- val mask: usize = map.cap - 1- val h: u64 = hash_oid(oid)- val idx: mut usize = (h as usize) & mask- for {- if !used_at(map, idx) {- set_used(map, idx)- copy_key(map, idx, oid)- copy_value(map, idx, value)- map.len++- return- }- if slot_eql(map, idx, oid) {- copy_value(map, idx, value)- return- }- idx = (idx + 1) & mask- }-}--fn grow(map: mut OidMap) void = trust {- val old_slots: mut ref u8 = map.slots- val old_cap: usize = map.cap- val new_cap: usize = old_cap * 2- val p: ref u8 = @alloc(new_cap * SLOT_LEN) as ref u8- @memset(p as ref void, 0, new_cap * SLOT_LEN)- map.slots = p- map.cap = new_cap- map.len = 0- val i: mut usize = 0- for i < old_cap {- if @load8(@ptradd(old_slots, (i * SLOT_LEN) as i64)) != 0 {- val op: bytes.Bytes = bytes.bytes(- @ptradd(old_slots, (i * SLOT_LEN + 1) as i64),- OID_LEN- )- val vp: bytes.Bytes = bytes.bytes(- @ptradd(old_slots, (i * SLOT_LEN + 1 + OID_LEN) as i64),- VALUE_LEN- )- insert_slot(map, op, vp)- }- i++- }- @free(old_slots as ref void)-}--/// Insert or replace an entry. An empty `value` records membership only.-pub fn put(map: mut OidMap, oid: bytes.Bytes, value: bytes.Bytes) void = trust {- pre {- oid_len: oid.len == OID_LEN- value_len: value.len == 0 || value.len <= VALUE_LEN- }- if (map.len + 1) * 10 >= map.cap * 7 {- grow(map)- }- insert_slot(map, oid, value)-}--pub fn get(map: OidMap, oid: bytes.Bytes) option[bytes.Bytes] = trust {- pre {- oid_len: oid.len == OID_LEN- }- if map.cap == 0 {- return none- }- val mask: usize = map.cap - 1- val h: u64 = hash_oid(oid)- val idx: mut usize = (h as usize) & mask- for {- if !used_at(map, idx) {- return none- }- if slot_eql(map, idx, oid) {- return some bytes.bytes(value_ptr(map, idx), VALUE_LEN)- }- idx = (idx + 1) & mask- }- return none-}--pub fn contains(map: OidMap, oid: bytes.Bytes) bool = trust {- if get(map, oid) is some _ {- return true- }- return false-}--pub fn slot_used(map: OidMap, i: usize) bool = trust {- pre {- in_bounds: i < map.cap- }- return used_at(map, i)-}--pub fn slot_oid(map: OidMap, i: usize) bytes.Bytes = trust {- pre {- in_bounds: i < map.cap- }- return bytes.bytes(oid_ptr(map, i), OID_LEN)-}--pub fn slot_value(map: OidMap, i: usize) bytes.Bytes = trust {- pre {- in_bounds: i < map.cap- }- return bytes.bytes(value_ptr(map, i), VALUE_LEN)-}--- a/src/src/git/refs.sx+++ /dev/null@@ -1,284 +0,0 @@-/// Read refs and HEAD directly from a git directory.--val str = use("std/string")-val bytes = use("../core/bytes.sx")-val lists = use("../core/lists.sx")-val files = use("../io/files.sx")--pub type Ref = {- name: mut bytes.Bytes- oid: mut bytes.Bytes-}--pub type RefSet = {- branches: mut list[ref Ref]- tags: mut list[ref Ref]- head: mut bytes.Bytes-}--fn new_ref(name: bytes.Bytes, oid: bytes.Bytes) ref Ref = trust {- val r: mut ref Ref = @alloc(@sizeof(Ref)) as ref Ref- r.name = name- r.oid = oid- return r-}--fn hex_value(c: u8) i32 = trust {- 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-}--pub fn parse_hex_oid(text: bytes.Bytes) option[bytes.Bytes] = trust {- if text.len != 40 {- return none- }- val out: ref u8 = @alloc(20) as ref u8- val i: mut usize = 0- for i < 20 {- val hi: i32 = hex_value(bytes.Bytes.at(text, i * 2))- val lo: i32 = hex_value(bytes.Bytes.at(text, i * 2 + 1))- if hi < 0 || lo < 0 {- @free(out as ref void)- return none- }- @store8(@ptradd(out, i as i64), ((hi * 16 + lo) as u8))- i++- }- return some bytes.bytes(out, 20)-}--fn trim_eol(data: bytes.Bytes) bytes.Bytes = trust {- val end: mut usize = data.len- for end > 0 && (bytes.Bytes.at(data, end - 1) == 10 || bytes.Bytes.at(data, end - 1) == 13) {- end--- }- return bytes.Bytes.slice(data, 0, end)-}--fn read_line_file(path: str.StringView) option[bytes.Bytes] = trust {- val data_opt = files.read_all(path)- match data_opt {- some d => {- return some trim_eol(d)- }- none => {- return none- }- }-}--fn starts_with(data: bytes.Bytes, prefix: bytes.Bytes) bool = trust {- return bytes.Bytes.starts_with(data, prefix)-}--fn find_ref(refs: list[ref Ref], name: bytes.Bytes) option[bytes.Bytes] = trust {- for r in refs {- if bytes.Bytes.eql(r.name, name) {- return some r.oid- }- }- return none-}--fn replace_ref(refs: mut list[ref Ref], name: bytes.Bytes, oid: bytes.Bytes) void = trust {- val i: mut usize = 0- for i < @len(refs) {- val o = @get(refs, i)- if o is some r {- if bytes.Bytes.eql(r.name, name) {- r.oid = oid- return- }- }- i++- }- @append(refs, new_ref(bytes.Bytes.dup(name), oid))-}--fn short_name(full: bytes.Bytes, prefix_len: usize) bytes.Bytes = trust {- return bytes.Bytes.slice(full, prefix_len, full.len)-}--fn read_packed_refs(- git_dir: str.StringView,- branches: mut list[ref Ref],- tags: mut list[ref Ref]-) void = trust {- val path: str.StringView = files.join(git_dir, str.from_cstr(c"packed-refs"))- val data_opt = files.read_all(path)- files.free_path(path)- val data: mut bytes.Bytes = bytes.empty()- match data_opt {- some d => {- data = d- }- none => {- return- }- }- val pos: mut usize = 0- for pos < data.len {- val end: mut usize = pos- for end < data.len && bytes.Bytes.at(data, end) != 10 {- end++- }- val line: bytes.Bytes = bytes.Bytes.slice(data, pos, end)- pos = end + 1- if line.len == 0 || bytes.Bytes.at(line, 0) == 35 || bytes.Bytes.at(line, 0) == 94 {- continue- }- val space: mut usize = 0- for space < line.len && bytes.Bytes.at(line, space) != 32 {- space++- }- if space == 0 || space >= line.len {- continue- }- val hex: bytes.Bytes = bytes.Bytes.slice(line, 0, space)- val name: bytes.Bytes = bytes.Bytes.slice(line, space + 1, line.len)- val oid_opt = parse_hex_oid(hex)- if oid_opt is some oid {- if starts_with(name, bytes.bytes(c"refs/heads/", 11)) {- replace_ref(branches, short_name(name, 11), oid)- } elif starts_with(name, bytes.bytes(c"refs/tags/", 10)) {- replace_ref(tags, short_name(name, 10), oid)- }- }- }- files.free_buffer(data)-}--fn read_ref_dir(- base: str.StringView,- rel: str.StringView,- refs: mut list[ref Ref]-) void = trust {- val dir: mut str.StringView = base- if rel.len != 0 {- dir = files.join(base, rel)- }- val names: list[ref u8] = files.list_dir(dir)- for n in names {- val nv: str.StringView = str.from_cstr(n)- val child_rel: mut str.StringView = files.with_suffix(nv, str.view(none, 0))- if rel.len != 0 {- files.free_path(child_rel)- child_rel = files.join3(rel, str.from_cstr(c"/"), nv)- }- val child_path: str.StringView = files.join(base, child_rel)- if files.exists_dir(child_path) {- read_ref_dir(base, child_rel, refs)- } else {- val content_opt = read_line_file(child_path)- if content_opt is some content {- val oid_opt = parse_hex_oid(content)- if oid_opt is some oid {- replace_ref(refs, bytes.Bytes.dup(bytes.from_cstr(child_rel.ptr)), oid)- }- }- }- files.free_path(child_rel)- files.free_path(child_path)- }- files.free_names(names)- if rel.len != 0 {- files.free_path(dir)- }-}--fn resolve_head(- git_dir: str.StringView,- branches: list[ref Ref],- tags: list[ref Ref]-) bytes.Bytes = trust {- val path: str.StringView = files.join(git_dir, str.from_cstr(c"HEAD"))- val data_opt = read_line_file(path)- files.free_path(path)- val data: mut bytes.Bytes = bytes.empty()- match data_opt {- some d => {- data = d- }- none => {- return bytes.empty()- }- }- if starts_with(data, bytes.bytes(c"ref: ", 5)) {- val name: bytes.Bytes = bytes.Bytes.slice(data, 5, data.len)- if starts_with(name, bytes.bytes(c"refs/heads/", 11)) {- val short: bytes.Bytes = short_name(name, 11)- val found = find_ref(branches, short)- if found is some oid {- files.free_buffer(data)- return bytes.Bytes.dup(oid)- }- }- if starts_with(name, bytes.bytes(c"refs/tags/", 10)) {- val short2: bytes.Bytes = short_name(name, 10)- val found2 = find_ref(tags, short2)- if found2 is some oid {- files.free_buffer(data)- return bytes.Bytes.dup(oid)- }- }- files.free_buffer(data)- return bytes.empty()- }- val oid_opt = parse_hex_oid(data)- files.free_buffer(data)- match oid_opt {- some oid => {- return oid- }- none => {- return bytes.empty()- }- }-}--pub fn read(git_dir: str.StringView) RefSet = trust {- val branches: mut list[ref Ref] = lists.new[ref Ref]()- val tags: mut list[ref Ref] = lists.new[ref Ref]()- read_packed_refs(git_dir, branches, tags)- val heads_base: str.StringView = files.join(git_dir, str.from_cstr(c"refs/heads"))- read_ref_dir(heads_base, str.view(none, 0), branches)- files.free_path(heads_base)- val tags_base: str.StringView = files.join(git_dir, str.from_cstr(c"refs/tags"))- read_ref_dir(tags_base, str.view(none, 0), tags)- files.free_path(tags_base)- val head: bytes.Bytes = resolve_head(git_dir, branches, tags)- return RefSet{branches: branches, tags: tags, head: head}-}--fn free_refs(refs: list[ref Ref]) void = trust {- for r in refs {- if r.name.ptr != none {- val np: mut ref void = r.name.ptr as ref void- @free(np)- }- if r.oid.ptr != none {- val op: mut ref void = r.oid.ptr as ref void- @free(op)- }- val rp: mut ref void = r as ref void- @free(rp)- }- @listfree(refs)-}--pub fn free(set: RefSet) void = trust {- free_refs(set.branches)- free_refs(set.tags)- if set.head.ptr != none {- val hp: mut ref void = set.head.ptr as ref void- @free(hp)- }-}--- a/src/src/io/files.sx+++ /dev/null@@ -1,215 +0,0 @@-/// 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--- }- 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 > 8589934592 {- 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++- }- return true-}--- a/src/src/io/native.sx+++ /dev/null@@ -1,185 +0,0 @@-/// 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"-extern (C) fn lseek(fd: i32, offset: i64, whence: i32) i64 = "lseek"-extern (C) fn pwrite(fd: i32, buf: ref void, n: usize, offset: i64) i64 = "pwrite"-extern (C) fn read(fd: i32, buf: ref void, n: usize) i64 = "read"-extern (C) fn unlink(path: ref u8) i32 = "unlink"--val O_WRONLY: i32 = 1-val O_RDWR: i32 = 2-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-}--/// Write all of `data` to an already-open descriptor.-pub fn write_fd_all(fd: i32, data: bytes.Bytes) bool = trust {- return write_all_fd(fd, data)-}--/// Open a file for reading and writing, creating or truncating it.-pub fn open_rw(path: str.StringView) i32 = trust {- val z: str.ZString = zstr(path)- if z.ptr == none {- return -1- }- val fd: i32 = open(z.ptr, O_RDWR | O_CREAT | O_TRUNC, MODE)- free_z(z)- return fd-}--/// Write at an absolute offset, retrying short writes.-pub fn pwrite_fd_all(fd: i32, offset: i64, data: bytes.Bytes) bool = trust {- val done: mut usize = 0- for done < data.len {- val p: ref void = @ptradd(data.ptr, done as i64) as ref void- val n: i64 = pwrite(fd, p, data.len - done, offset + done as i64)- if n <= 0 {- return false- }- done = done + n as usize- }- return true-}--/// Read up to `n` bytes into `buf`.-pub fn read_fd(fd: i32, buf: ref u8, n: usize) i64 = trust {- return read(fd, buf as ref void, n)-}--pub fn seek_set(fd: i32, offset: i64) bool = trust {- return lseek(fd, offset, 0) == offset-}--pub fn fsync_fd(fd: i32) bool = trust {- return fsync(fd) == 0-}--pub fn close_fd(fd: i32) void = trust {- val _ = close(fd)-}--pub fn rename_file(oldp: str.StringView, newp: str.StringView) bool = trust {- val oz: str.ZString = zstr(oldp)- val nz: str.ZString = zstr(newp)- if oz.ptr == none || nz.ptr == none {- free_z(oz)- free_z(nz)- return false- }- val rc: i32 = rename(oz.ptr, nz.ptr)- free_z(oz)- free_z(nz)- return rc == 0-}--pub fn delete_file(path: str.StringView) bool = trust {- val z: str.ZString = zstr(path)- if z.ptr == none {- return false- }- val rc: i32 = unlink(z.ptr)- free_z(z)- return rc == 0-}--/// Flush a directory entry change.-pub fn sync_dir_path(dir: str.StringView) bool = trust {- return sync_dir(dir)-}--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/io/stat.sx+++ /dev/null@@ -1,120 +0,0 @@-/// Minimal `lstat`/`readlink` helpers used by working-copy snapshots.-///-/// The C `struct stat` layout differs by platform, so only the fields the-/// snapshot code needs are read, from the offsets used by the hosted runtimes-/// veins targets.--val str = use("std/string")-val allocators = use("std/allocators")-val bytes = use("../core/bytes.sx")--extern (C) fn lstat(path: ref u8, buf: ref void) i32 = "lstat"-extern (C) fn readlink(path: ref u8, buf: ref u8, n: usize) i64 = "readlink"--pub val KIND_MISSING: u8 = 0-pub val KIND_FILE: u8 = 1-pub val KIND_DIR: u8 = 2-pub val KIND_LINK: u8 = 3--pub type StatInfo = {- kind: mut u8- executable: mut bool- size: mut u64- mtime_ns: mut u64- inode: mut u64-}--fn heap() allocators.HeapAllocator = trust {- return @zeroed-}--fn zstr(p: str.StringView) str.ZString = trust {- return str.zstr_from[allocators.HeapAllocator](heap(), p)-}--fn free_z(z: str.ZString) void = trust {- str.zstr_free[allocators.HeapAllocator](heap(), z)-}--fn kind_from_mode(mode: u32) u8 = trust {- val masked: u32 = mode & 61440- if masked == 16384 {- return KIND_DIR- }- if masked == 32768 {- return KIND_FILE- }- if masked == 40960 {- return KIND_LINK- }- return KIND_MISSING-}--pub fn read(path: str.StringView) option[StatInfo] = trust {- val z: str.ZString = zstr(path)- if z.ptr == none {- return none- }- val buf: ref u8 = @alloc(320) as ref u8- @memset(buf as ref void, 0, 320)- val rc: i32 = lstat(z.ptr, buf as ref void)- free_z(z)- if rc != 0 {- @free(buf as ref void)- return none- }- val info: mut StatInfo = StatInfo{- kind: KIND_MISSING,- executable: false,- size: 0,- mtime_ns: 0,- inode: 0- }- when linux {- val mode: u32 = @load32(@ptradd(buf, 24) as ref void) as u32- info.kind = kind_from_mode(mode)- info.executable = (mode & 73) != 0- info.inode = @load64(@ptradd(buf, 8) as ref void) as u64- info.size = @load64(@ptradd(buf, 48) as ref void) as u64- val sec: u64 = @load64(@ptradd(buf, 88) as ref void) as u64- val nsec: u64 = @load64(@ptradd(buf, 96) as ref void) as u64- info.mtime_ns = sec * 1000000000 + nsec- }- or when darwin {- val mode2: u32 = @load16(@ptradd(buf, 4) as ref void) as u32- info.kind = kind_from_mode(mode2)- info.executable = (mode2 & 73) != 0- info.inode = @load64(@ptradd(buf, 8) as ref void) as u64- info.size = @load64(@ptradd(buf, 96) as ref void) as u64- val sec2: u64 = @load64(@ptradd(buf, 48) as ref void) as u64- val nsec2: u64 = @load64(@ptradd(buf, 56) as ref void) as u64- info.mtime_ns = sec2 * 1000000000 + nsec2- }- otherwise {- info.kind = KIND_FILE- info.executable = false- info.inode = 0- val sz = trust @load64(@ptradd(buf, 48) as ref void) as u64- info.size = sz- info.mtime_ns = 0- }- @free(buf as ref void)- return some info-}--/// Read a symlink target. The result is owned by the caller.-pub fn link_target(path: str.StringView) option[bytes.Bytes] = trust {- val z: str.ZString = zstr(path)- if z.ptr == none {- return none- }- val cap: usize = 65537- val buf: ref u8 = @alloc(cap) as ref u8- val n: i64 = readlink(z.ptr, buf, cap - 1)- free_z(z)- if n < 0 {- @free(buf as ref void)- return none- }- return some bytes.bytes(buf, n as usize)-}--- a/src/src/main.sx+++ /dev/null@@ -1,480 +0,0 @@-lib "z"-lib "crypto"--val stdio = use("std/stdio")-val str = use("std/string")-val msg = use("core/msg.sx")-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")-val git_cmd = use("cli/git_cmd.sx")-val checkout_cmd = use("cli/checkout_cmd.sx")-val help_cmd = use("cli/help_cmd.sx")-val bench_cmd = use("cli/bench_cmd.sx")-val status_cmd = use("cli/status_cmd.sx")-val log_cmd = use("cli/log_cmd.sx")-val diff_cmd = use("cli/diff_cmd.sx")-val new_cmd = use("cli/new_cmd.sx")-val op_cmd = use("cli/op_cmd.sx")-val lists = use("core/lists.sx")-val layout = use("store/layout.sx")--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 is_flag(a: ref u8) bool = trust {- if a == none {- return false- }- if @strlen(a) == 0 {- return false- }- return @load8(a) == 45-}--fn run_init(args: list[ref u8], start: usize) i32 = trust {- val mut_path: mut str.StringView = str.from_cstr(c".")- val source: mut option[str.StringView] = none- val i: mut usize = start- for i < @len(args) {- val o = @get(args, i)- if o is some a {- val av: bytes.Bytes = bytes.from_cstr(a)- val prefix: bytes.Bytes = bytes.bytes(c"-git-import:", 12)- if bytes.Bytes.starts_with(av, prefix) {- if av.len == 12 {- msg.error_prefix()- stdio.eprint("-git-import: requires a path\n", {})- return 1- }- val value: bytes.Bytes = bytes.Bytes.slice(av, 12, av.len)- source = some str.view(value.ptr, value.len as i64)- } elif av.len > 0 && bytes.Bytes.at(av, 0) == 45 {- msg.error_prefix()- stdio.eprint("unknown flag: {s}\n", {str.from_cstr(a)})- return 1- } else {- mut_path = str.from_cstr(a)- }- i++- } else {- i++- }- }- return init_cmd.run(mut_path, source)-}--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 end_flags: mut bool = false- val i: mut usize = start- for i < @len(args) {- val o = @get(args, i)- if o is some a {- if !end_flags && cmd_is(a, c"--", 2) {- end_flags = true- } elif !end_flags && (cmd_is(a, c"-v", 2) || cmd_is(a, c"-verbose", 8)) {- verbose = true- } elif !end_flags && is_flag(a) {- msg.error_prefix()- stdio.eprint("unknown flag: {s}\n", {str.from_cstr(a)})- return 1- } else {- mut_path = str.from_cstr(a)- }- }- i++- }- return fsck_cmd.run(mut_path, verbose)-}---fn open_repo_or_error(path: str.StringView) option[layout.Repo] = trust {- val repo_opt = layout.discover(path)- match repo_opt {- some repo => {- return some repo- }- none => {- msg.error_prefix()- stdio.eprint("not a veins repository\n", {})- return none- }- }-}--fn run_status() i32 = trust {- val repo_opt = open_repo_or_error(str.from_cstr(c"."))- match repo_opt {- some repo => {- val status: i32 = status_cmd.run(repo)- layout.free_repo(repo)- return status- }- none => {- return 1- }- }-}--fn run_log(args: list[ref u8], start: usize) i32 = trust {- val rev: mut bytes.Bytes = bytes.empty()- val col_titles: mut bool = true- val end_flags: mut bool = false- val i: mut usize = start- for i < @len(args) {- val o = @get(args, i)- if o is some a {- if !end_flags && cmd_is(a, c"--", 2) {- end_flags = true- } elif !end_flags && (cmd_is(a, c"-r", 2) || cmd_is(a, c"-rev", 4)) {- if i + 1 < @len(args) {- val v = @get(args, i + 1)- if v is some rv {- rev = bytes.from_cstr(rv)- i++- }- } else {- msg.error_prefix()- stdio.eprint("{s} requires a revision\n", {str.from_cstr(a)})- return 1- }- } elif !end_flags && cmd_is(a, c"-no-col-titles", 14) {- col_titles = false- } elif !end_flags && is_flag(a) {- msg.error_prefix()- stdio.eprint("unknown flag: {s}\n", {str.from_cstr(a)})- return 1- } else {- rev = bytes.from_cstr(a)- }- }- i++- }- val repo_opt = open_repo_or_error(str.from_cstr(c"."))- match repo_opt {- some repo => {- val status: i32 = log_cmd.run(repo, rev, col_titles)- layout.free_repo(repo)- return status- }- none => {- return 1- }- }-}--fn run_diff(args: list[ref u8], start: usize) i32 = trust {- val revs: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()- val end_flags: mut bool = false- val i: mut usize = start- for i < @len(args) {- val o = @get(args, i)- if o is some a {- if !end_flags && cmd_is(a, c"--", 2) {- end_flags = true- } elif !end_flags && (cmd_is(a, c"-r", 2) || cmd_is(a, c"-rev", 4)) {- if i + 1 < @len(args) {- val v = @get(args, i + 1)- if v is some rv {- @append(revs, bytes.from_cstr(rv))- i++- }- } else {- msg.error_prefix()- stdio.eprint("{s} requires a revision\n", {str.from_cstr(a)})- @listfree(revs)- return 1- }- } elif !end_flags && is_flag(a) {- msg.error_prefix()- stdio.eprint("unknown flag: {s}\n", {str.from_cstr(a)})- @listfree(revs)- return 1- } else {- @append(revs, bytes.from_cstr(a))- }- }- i++- }- val repo_opt = open_repo_or_error(str.from_cstr(c"."))- match repo_opt {- some repo => {- val status: i32 = diff_cmd.run(repo, revs)- layout.free_repo(repo)- @listfree(revs)- return status- }- none => {- @listfree(revs)- return 1- }- }-}--fn run_new(args: list[ref u8], start: usize) i32 = trust {- val revs: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()- val end_flags: mut bool = false- val i: mut usize = start- for i < @len(args) {- val o = @get(args, i)- if o is some a {- if !end_flags && cmd_is(a, c"--", 2) {- end_flags = true- } elif !end_flags && is_flag(a) {- msg.error_prefix()- stdio.eprint("unknown flag: {s}\n", {str.from_cstr(a)})- @listfree(revs)- return 1- } else {- @append(revs, bytes.from_cstr(a))- }- }- i++- }- val repo_opt = open_repo_or_error(str.from_cstr(c"."))- match repo_opt {- some repo => {- val status: i32 = new_cmd.new_change(repo, revs)- layout.free_repo(repo)- @listfree(revs)- return status- }- none => {- @listfree(revs)- return 1- }- }-}--fn parse_message(args: list[ref u8], start: usize) result[list[bytes.Bytes], i32] = trust {- val parts: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()- val end_flags: mut bool = false- val i: mut usize = start- for i < @len(args) {- val o = @get(args, i)- if o is some a {- if !end_flags && cmd_is(a, c"--", 2) {- end_flags = true- } elif !end_flags && (cmd_is(a, c"-m", 2) || cmd_is(a, c"-message", 8)) {- if i + 1 < @len(args) {- val v = @get(args, i + 1)- if v is some rv {- @append(parts, bytes.from_cstr(rv))- i++- }- } else {- msg.error_prefix()- stdio.eprint("{s} requires a message\n", {str.from_cstr(a)})- @listfree(parts)- return err 1- }- } elif !end_flags && is_flag(a) {- msg.error_prefix()- stdio.eprint("unknown flag: {s}\n", {str.from_cstr(a)})- @listfree(parts)- return err 1- } else {- @append(parts, bytes.from_cstr(a))- }- }- i++- }- return ok parts-}--fn run_describe(args: list[ref u8], start: usize) i32 = trust {- val parsed = parse_message(args, start)- val parts: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()- match parsed {- ok x => {- parts = x- }- err code => {- return code- }- }- val repo_opt = open_repo_or_error(str.from_cstr(c"."))- match repo_opt {- some repo => {- val status: i32 = new_cmd.describe(repo, parts)- layout.free_repo(repo)- @listfree(parts)- return status- }- none => {- @listfree(parts)- return 1- }- }-}--fn run_commit(args: list[ref u8], start: usize) i32 = trust {- val parsed = parse_message(args, start)- val parts: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()- match parsed {- ok x => {- parts = x- }- err code => {- return code- }- }- val repo_opt = open_repo_or_error(str.from_cstr(c"."))- match repo_opt {- some repo => {- val n: i32 = new_cmd.commit_changes(repo, parts)- @listfree(parts)- layout.free_repo(repo)- return n- }- none => {- @listfree(parts)- return 1- }- }-}--fn run_undo() i32 = trust {- val repo_opt = open_repo_or_error(str.from_cstr(c"."))- match repo_opt {- some repo => {- val status: i32 = op_cmd.undo(repo)- layout.free_repo(repo)- return status- }- none => {- return 1- }- }-}--fn run_op(args: list[ref u8], start: usize) i32 = trust {- val sub_opt = @get(args, start)- val sub: mut ref u8 = none- match sub_opt {- some s => {- sub = s- }- none => {- msg.error_prefix()- stdio.eprint("expected an op subcommand (log, restore, revert)\n", {})- return 1- }- }- val repo_opt = open_repo_or_error(str.from_cstr(c"."))- val repo: mut layout.Repo = layout.Repo{root: @zeroed}- match repo_opt {- some r => {- repo = r- }- none => {- return 1- }- }- val status: mut i32 = 1- if cmd_is(sub, c"log", 3) {- status = op_cmd.log(repo)- } elif cmd_is(sub, c"restore", 7) {- val o = @get(args, start + 1)- if o is some t {- status = op_cmd.restore(repo, bytes.from_cstr(t))- } else {- msg.error_prefix()- stdio.eprint("op restore requires an operation id\n", {})- }- } elif cmd_is(sub, c"revert", 6) {- val o = @get(args, start + 1)- if o is some t {- status = op_cmd.revert(repo, bytes.from_cstr(t))- } else {- msg.error_prefix()- stdio.eprint("op revert requires an operation id\n", {})- }- } else {- msg.error_prefix()- stdio.eprint("unknown op subcommand: {s}\n", {str.from_cstr(sub)})- }- layout.free_repo(repo)- return status-}--pub fn main() i32 = trust {- val args: list[ref u8] = @args()- if @len(args) < 2 {- help_cmd.usage()- return 1- }- val cmd_opt = @get(args, 1)- val cmd: mut ref u8 = none- match cmd_opt {- some c => {- cmd = c- }- none => {- help_cmd.usage()- return 1- }- }-- if cmd_is(cmd, c"init", 4) {- return run_init(args, 2)- }- if cmd_is(cmd, c"git", 3) {- return git_cmd.run(args, 2)- }- if cmd_is(cmd, c"checkout", 8) {- return checkout_cmd.run(args, 2)- }- if cmd_is(cmd, c"status", 6) {- return run_status()- }- if cmd_is(cmd, c"log", 3) {- return run_log(args, 2)- }- if cmd_is(cmd, c"diff", 4) {- return run_diff(args, 2)- }- if cmd_is(cmd, c"new", 3) {- return run_new(args, 2)- }- if cmd_is(cmd, c"describe", 8) {- return run_describe(args, 2)- }- if cmd_is(cmd, c"commit", 6) {- return run_commit(args, 2)- }- if cmd_is(cmd, c"undo", 4) {- return run_undo()- }- if cmd_is(cmd, c"op", 2) {- return run_op(args, 2)- }- if cmd_is(cmd, c"fsck", 4) {- return run_fsck(args, 2)- }- if cmd_is(cmd, c"self-test", 9) {- return selftest_cmd.run()- }- if cmd_is(cmd, c"version", 7) || cmd_is(cmd, c"-version", 8) {- stdio.puts("vn 0.0.1 (veins-store 1)")- return 0- }- if cmd_is(cmd, c"bench-import", 12) {- return bench_cmd.run(args, 2)- }- if cmd_is(cmd, c"help", 4) || cmd_is(cmd, c"-help", 5) || cmd_is(cmd, c"-h", 2) {- return help_cmd.run(args, 2)- }-- msg.error_prefix()- stdio.eprint("unknown command: {s}\n", {str.from_cstr(cmd)})- help_cmd.usage()- return 1-}--- a/src/src/object/blob.sx+++ /dev/null@@ -1,300 +0,0 @@-/// 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++- }- 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++- }- 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++- }- 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++- }- 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 = trust {- 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)- val ro: mut ref raw.RawObject = raw.raw(types.BLOB, owned)- ro.id = root.ptr- @append(objects, ro)- 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(@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)- val ro: mut ref raw.RawObject = raw.raw(types.CHUNK, bytes.Bytes.dup(chunk))- ro.id = cid.ptr- @append(objects, ro)- @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)- val ro: mut ref raw.RawObject = raw.raw(types.BLOB, owned)- ro.id = nid.ptr- @append(objects, ro)- @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)-}--- a/src/src/object/changeid.sx+++ /dev/null@@ -1,69 +0,0 @@-/// Lowercase RFC 4648 base32 rendering for change IDs.--val bytes = use("../core/bytes.sx")-val objid = use("../object/id.sx")--fn alphabet() bytes.Bytes = trust {- return bytes.bytes(c"abcdefghijklmnopqrstuvwxyz234567", 32)-}--/// Full base32 encoding of a 16-byte change ID. No padding is added.-pub fn encode(cid: objid.ChangeId) bytes.Bytes = trust {- val out: ref u8 = @alloc(32) as ref u8- val alpha: bytes.Bytes = alphabet()- val bufv: mut u64 = 0- val bits: mut usize = 0- val n: mut usize = 0- val i: mut usize = 0- for i < objid.CHANGE_ID_LEN {- val c: u8 = @load8(@ptradd(cid.ptr, i as i64))- bufv = (bufv << 8) | (c as u64)- bits = bits + 8- for bits >= 5 {- val shift: usize = bits - 5- val idx: usize = ((bufv >> shift) & 31) as usize- @store8(@ptradd(out, n as i64), bytes.Bytes.at(alpha, idx))- n++- bits = shift- }- if bits == 0 {- bufv = 0- } else {- bufv = bufv & ((1 as u64 << bits) - 1)- }- i++- }- if bits > 0 {- val idx2: usize = ((bufv << (5 - bits)) & 31) as usize- @store8(@ptradd(out, n as i64), bytes.Bytes.at(alpha, idx2))- n++- }- return bytes.bytes(out, n)-}--pub fn prefix_matches(full: bytes.Bytes, text: bytes.Bytes) bool = trust {- if text.len == 0 || text.len > full.len {- return false- }- val i: mut usize = 0- for i < text.len {- val a: u8 = bytes.Bytes.at(full, i)- val c: u8 = bytes.Bytes.at(text, i)- val lower: mut u8 = c- if c >= 65 && c <= 90 {- lower = (c + 32) as u8- }- if a != lower {- return false- }- i++- }- return true-}--pub fn free(cid: bytes.Bytes) void = trust {- if cid.ptr != none {- val p: mut ref void = cid.ptr as ref void- @free(p)- }-}--- a/src/src/object/commit.sx+++ /dev/null@@ -1,222 +0,0 @@-/// 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++- }- 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++- }- 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++- }- 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++- }- 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)-}--- a/src/src/object/conflict.sx+++ /dev/null@@ -1,168 +0,0 @@-/// 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++- }- 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)-}--- a/src/src/object/content.sx+++ /dev/null@@ -1,113 +0,0 @@-/// Materialize a blob into memory for diff and inspection commands.--val bytes = use("../core/bytes.sx")-val buf = use("../core/buf.sx")-val objid = use("../object/id.sx")-val types = use("../object/types.sx")-val blob = use("../object/blob.sx")-val state = use("../store/state.sx")-val store = use("../store/store.sx")-val files = use("../io/files.sx")-val lazy = use("../git/lazy.sx")-val object = use("../git/object.sx")--fn append_blob(- handles: list[ref store.Handle],- out: mut buf.Buf,- id: objid.Id,- depth: usize,- git: object.GitRepo,- has_git: bool-) bool = trust {- if depth > 64 {- return false- }- if lazy.is_lazy(id) {- if !has_git {- return false- }- val read = object.read_fast(git, lazy.git_oid(id))- match read {- ok o => {- val read_ok: mut bool = false- if o.kind == object.KIND_BLOB {- buf.Buf.put_bytes(out, o.body)- read_ok = true- }- object.free_object(o)- return read_ok- }- err _ => {- return false- }- }- }- val body_opt = state.read_body(handles, id, types.BLOB)- val body: mut bytes.Bytes = bytes.empty()- match body_opt {- some b => {- body = b- }- none => {- return false- }- }- val decoded = blob.decode(body)- val b: mut ref blob.Blob = none- match decoded {- ok x => {- b = x- }- err _ => {- files.free_buffer(body)- return false- }- }- val good: mut bool = true- if b.form == blob.FORM_INLINE {- buf.Buf.put_bytes(out, b.data)- } elif b.form == blob.FORM_LEAF {- for e in b.entries {- val chunk_opt = state.read_body(handles, e.id, types.CHUNK)- match chunk_opt {- some chunk => {- buf.Buf.put_bytes(out, chunk)- files.free_buffer(chunk)- }- none => {- good = false- }- }- if !good {- break- }- }- } else {- for e in b.entries {- if !append_blob(handles, out, e.id, depth + 1, git, has_git) {- good = false- break- }- }- }- blob.free_blob(b)- files.free_buffer(body)- return good-}--/// Read the full content of a blob. The returned bytes are owned by the caller.-pub fn read_blob(- handles: list[ref store.Handle],- id: objid.Id,- git: object.GitRepo,- has_git: bool-) option[bytes.Bytes] = trust {- val out: mut buf.Buf = buf.new(4096)- val good: bool = append_blob(handles, out, id, 0, git, has_git)- val result: mut option[bytes.Bytes] = none- if good {- result = some(bytes.Bytes.dup(buf.Buf.view(out)))- }- buf.Buf.free(out)- return result-}--- a/src/src/object/graph.sx+++ /dev/null@@ -1,308 +0,0 @@-/// Commit graph traversal and revision resolution.--val bytes = use("../core/bytes.sx")-val lists = use("../core/lists.sx")-val objid = use("../object/id.sx")-val types = use("../object/types.sx")-val commit = use("../object/commit.sx")-val tree = use("../object/tree.sx")-val treewalk = use("../object/treewalk.sx")-val view = use("../object/view.sx")-val changeid = use("changeid.sx")-val state = use("../store/state.sx")-val store = use("../store/store.sx")-val files = use("../io/files.sx")-val viewops = use("../store/viewops.sx")--pub fn copy_id(id: objid.Id) objid.Id = trust {- val out: ref u8 = @alloc(32) as ref u8- @memcpy(out as ref void, id.ptr as ref void, 32)- return objid.id(out)-}--pub fn contains(ids: list[objid.Id], id: objid.Id) bool = trust {- for x in ids {- if objid.Id.eql(x, id) {- return true- }- }- return false-}--pub fn free_ids(ids: list[objid.Id]) void = trust {- for id in ids {- if id.ptr != none {- val p: mut ref void = id.ptr as ref void- @free(p)- }- }- @listfree(ids)-}--pub fn roots(v: ref view.View) list[objid.Id] = trust {- val out: mut list[objid.Id] = lists.new[objid.Id]()- for h in v.heads {- if !contains(out, h) {- @append(out, copy_id(h))- }- }- for bm in v.bookmarks {- for id in bm.targets.adds {- if !contains(out, id) {- @append(out, copy_id(id))- }- }- }- for t in v.tags {- if !contains(out, t.target) {- @append(out, copy_id(t.target))- }- }- for w in v.working_copies {- if !contains(out, w.target) {- @append(out, copy_id(w.target))- }- }- return out-}--pub type LoadedCommit = {- c: mut ref commit.Commit- body: mut bytes.Bytes-}--pub fn load_commit(- handles: list[ref store.Handle],- id: objid.Id-) option[ref LoadedCommit] = trust {- val body_opt = state.read_body(handles, id, types.COMMIT)- val body: mut bytes.Bytes = bytes.empty()- match body_opt {- some b => {- body = b- }- none => {- return none- }- }- val decoded = commit.decode(body)- match decoded {- ok c => {- val lc: mut ref LoadedCommit = @alloc(@sizeof(LoadedCommit)) as ref LoadedCommit- lc.c = c- lc.body = body- return some lc- }- err _ => {- files.free_buffer(body)- return none- }- }-}--pub fn free_loaded(lc: ref LoadedCommit) void = trust {- commit.free_commit(lc.c)- files.free_buffer(lc.body)- @free(lc as ref void)-}--/// True when the commit's tree differs from its first parent's tree.-pub fn has_changes(handles: list[ref store.Handle], lc: ref LoadedCommit) bool = trust {- if @len(lc.c.parents) > 0 {- val p = @get(lc.c.parents, 0)- val pid: mut objid.Id = objid.id_none()- if p is some x {- pid = x- }- val pl_opt = load_commit(handles, pid)- val changed: mut bool = true- if pl_opt is some parent {- changed = !objid.Id.eql(parent.c.root_tree, lc.c.root_tree)- free_loaded(parent)- }- return changed- }- val t_opt = treewalk.read_tree(handles, lc.c.root_tree)- val changed: mut bool = true- if t_opt is some t {- changed = @len(t.entries) > 0- tree.free_tree(t)- }- return changed-}--/// Collect all commits reachable from `start`.-pub fn collect(handles: list[ref store.Handle], start: list[objid.Id]) list[objid.Id] = trust {- val out: mut list[objid.Id] = lists.new[objid.Id]()- val stack: mut list[objid.Id] = lists.new[objid.Id]()- for id in start {- if !contains(out, id) && !contains(stack, id) {- @append(stack, copy_id(id))- }- }- for @len(stack) > 0 {- val id: objid.Id = @remove(stack, @len(stack) - 1)- if contains(out, id) {- val ip: mut ref void = id.ptr as ref void- @free(ip)- continue- }- @append(out, id)- val c_opt = load_commit(handles, id)- if c_opt is some lc {- for p in lc.c.parents {- if !contains(out, p) && !contains(stack, p) {- @append(stack, copy_id(p))- }- }- free_loaded(lc)- }- }- @listfree(stack)- return out-}--pub fn all(handles: list[ref store.Handle], v: ref view.View) list[objid.Id] = trust {- val rs: list[objid.Id] = roots(v)- val out: list[objid.Id] = collect(handles, rs)- free_ids(rs)- return out-}--fn is_hex_char(c: u8) bool = trust {- return (c >= 48 && c <= 57) || (c >= 97 && c <= 102) || (c >= 65 && c <= 70)-}--fn is_hex_prefix(b: bytes.Bytes) bool = trust {- if b.len < 4 || b.len > 64 {- return false- }- val i: mut usize = 0- for i < b.len {- if !is_hex_char(bytes.Bytes.at(b, i)) {- return false- }- i++- }- return true-}--fn id_matches_hex(id: objid.Id, text: bytes.Bytes) bool = trust {- val hex: ref u8 = objid.Id.hex(id)- val full: bytes.Bytes = bytes.bytes(hex, 64)- val matched: bool = changeid.prefix_matches(full, text)- @free(hex as ref void)- return matched-}--fn bookmark_target(v: ref view.View, name: bytes.Bytes) option[objid.Id] = trust {- for bm in v.bookmarks {- if bytes.Bytes.eql(bm.name, name) {- if @len(bm.targets.adds) == 1 {- val o = @get(bm.targets.adds, 0)- if o is some id {- return some id- }- }- return none- }- }- return none-}--fn tag_target(v: ref view.View, name: bytes.Bytes) option[objid.Id] = trust {- for t in v.tags {- if bytes.Bytes.eql(t.name, name) {- return some t.target- }- }- return none-}--fn remote_target(v: ref view.View, text: bytes.Bytes) option[objid.Id] = trust {- for rr in v.remote_refs {- val joined: usize = rr.remote.len + 1 + rr.name.len- if joined == text.len {- val prefix: bytes.Bytes = bytes.Bytes.slice(text, 0, rr.remote.len)- if bytes.Bytes.eql(prefix, rr.remote) && bytes.Bytes.at(text, rr.remote.len) == 47 {- val suffix: bytes.Bytes = bytes.Bytes.slice(- text,- rr.remote.len + 1,- text.len- )- if bytes.Bytes.eql(suffix, rr.name) {- return some rr.target- }- }- }- }- return none-}--pub fn resolve(- handles: list[ref store.Handle],- v: ref view.View,- rev: bytes.Bytes-) option[objid.Id] = trust {- if rev.len == 0 || bytes.Bytes.eql(rev, bytes.bytes(c"@", 1)) {- return viewops.working_copy(v)- }- val bm = bookmark_target(v, rev)- if bm is some id {- return some id- }- val tg = tag_target(v, rev)- if tg is some id2 {- return some id2- }- val rr = remote_target(v, rev)- if rr is some id3 {- return some id3- }- val ids: list[objid.Id] = all(handles, v)- val matches: mut list[objid.Id] = lists.new[objid.Id]()- if is_hex_prefix(rev) {- val i: mut usize = 0- for i < @len(ids) {- val o = @get(ids, i)- if o is some id4 {- if id_matches_hex(id4, rev) {- @append(matches, copy_id(id4))- }- }- i++- }- }- if @len(matches) == 0 {- val i2: mut usize = 0- for i2 < @len(ids) {- val o = @get(ids, i2)- if o is some id5 {- val c_opt = load_commit(handles, id5)- if c_opt is some lc {- if lc.c.change_id.ptr != none {- val encoded: bytes.Bytes = changeid.encode(lc.c.change_id)- if changeid.prefix_matches(encoded, rev) {- @append(matches, copy_id(id5))- }- changeid.free(encoded)- }- free_loaded(lc)- }- }- i2++- }- }- free_ids(ids)- val result: mut option[objid.Id] = none- if @len(matches) == 1 {- val o = @get(matches, 0)- if o is some only {- result = some copy_id(only)- }- } else {- // With divergent changes the change ID is ambiguous; callers report it.- }- free_ids(matches)- return result-}--- a/src/src/object/id.sx+++ /dev/null@@ -1,165 +0,0 @@-/// 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++- }-}--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++- }- 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 + 9)- buf.Buf.put_raw(b, c"veins/1", 7)- 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)-}--- a/src/src/object/names.sx+++ /dev/null@@ -1,81 +0,0 @@-/// 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-/// `.veins` 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++- }- if is_dot_name(b) {- return false- }- val veins: bytes.Bytes = bytes.bytes(c".veins", 6)- if bytes.Bytes.eql_ascii_ci(b, veins) {- 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++- }- 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++- }- return true-}--- a/src/src/object/operation.sx+++ /dev/null@@ -1,116 +0,0 @@-/// 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++- }- 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++- }- 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++- }- 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)-}--- a/src/src/object/raw.sx+++ /dev/null@@ -1,38 +0,0 @@-/// 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- id: mut ref u8-}--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- o.id = none- return o-}--pub fn free_objects(objects: list[ref RawObject]) void = {- for o in objects {- if o.body.ptr != none {- val body_ptr: mut ref void = o.body.ptr as ref void- trust @free(body_ptr)- }- if o.id != none {- val id_ptr: mut ref void = o.id as ref void- trust @free(id_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]()-}--- a/src/src/object/tree.sx+++ /dev/null@@ -1,155 +0,0 @@-/// 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]- body: mut bytes.Bytes-}--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++- }- 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]()- t.body = bytes.empty()- 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++- }- 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++- }- 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 = {- if t.body.ptr != none {- val bp: mut ref void = t.body.ptr as ref void- trust @free(bp)- }- 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)-}--- a/src/src/object/treediff.sx+++ /dev/null@@ -1,148 +0,0 @@-/// Sorted path-level comparison between two trees.--val bytes = use("../core/bytes.sx")-val lists = use("../core/lists.sx")-val objid = use("../object/id.sx")-val treewalk = use("treewalk.sx")-val store = use("../store/store.sx")--pub type Change = {- path: mut bytes.Bytes- old_kind: mut u8- new_kind: mut u8- old_id: mut objid.Id- new_id: mut objid.Id-}--fn copy_id(id: objid.Id) objid.Id = trust {- if id.ptr == none {- return objid.id(none)- }- val out: ref u8 = @alloc(32) as ref u8- @memcpy(out as ref void, id.ptr as ref void, 32)- return objid.id(out)-}--fn new_change(- path: bytes.Bytes,- old_kind: u8,- new_kind: u8,- oid: objid.Id,- nid: objid.Id-) ref Change = trust {- val c: mut ref Change = @alloc(@sizeof(Change)) as ref Change- c.path = path- c.old_kind = old_kind- c.new_kind = new_kind- c.old_id = copy_id(oid)- c.new_id = copy_id(nid)- return c-}--pub fn compare(- handles: list[ref store.Handle],- old_tree: option[objid.Id],- new_tree: option[objid.Id]-) list[ref Change] = trust {- val old = treewalk.flatten_or_empty(handles, old_tree)- val new = treewalk.flatten_or_empty(handles, new_tree)- val out: mut list[ref Change] = lists.new[ref Change]()- val i: mut usize = 0- val j: mut usize = 0- for i < @len(old) || j < @len(new) {- val take: mut i32 = 0- if i >= @len(old) {- take = 1- } elif j >= @len(new) {- take = -1- } else {- val o = @get(old, i)- val n = @get(new, j)- val op: mut bytes.Bytes = bytes.empty()- val np: mut bytes.Bytes = bytes.empty()- if o is some oo {- op = oo.path- }- if n is some nn {- np = nn.path- }- take = bytes.Bytes.cmp(op, np) as i32- }- if take < 0 {- val o = @get(old, i)- if o is some e {- @append(- out,- new_change(- bytes.Bytes.dup(e.path),- e.kind,- treewalk.KIND_MISSING,- e.target,- objid.id(none)- )- )- }- i++- } elif take > 0 {- val n = @get(new, j)- if n is some e2 {- @append(- out,- new_change(- bytes.Bytes.dup(e2.path),- treewalk.KIND_MISSING,- e2.kind,- objid.id(none),- e2.target- )- )- }- j++- } else {- val o = @get(old, i)- val n = @get(new, j)- if o is some e3 {- if n is some e4 {- val same: bool = e3.kind == e4.kind && objid.Id.eql(e3.target, e4.target)- if !same {- @append(- out,- new_change(- bytes.Bytes.dup(e3.path),- e3.kind,- e4.kind,- e3.target,- e4.target- )- )- }- }- }- i++- j++- }- }- treewalk.free_flat(old)- treewalk.free_flat(new)- return out-}--pub fn free(changes: list[ref Change]) void = trust {- for c in changes {- if c.path.ptr != none {- val pp: mut ref void = c.path.ptr as ref void- @free(pp)- }- if c.old_id.ptr != none {- val op: mut ref void = c.old_id.ptr as ref void- @free(op)- }- if c.new_id.ptr != none {- val np: mut ref void = c.new_id.ptr as ref void- @free(np)- }- val cp: mut ref void = c as ref void- @free(cp)- }- @listfree(changes)-}--- a/src/src/object/treewalk.sx+++ /dev/null@@ -1,287 +0,0 @@-/// Helpers for reading, flattening, and comparing tree objects.--val bytes = use("../core/bytes.sx")-val lists = use("../core/lists.sx")-val objid = use("../object/id.sx")-val types = use("../object/types.sx")-val tree = use("../object/tree.sx")-val read = use("../store/state.sx")-val store = use("../store/store.sx")-val files = use("../io/files.sx")--pub val KIND_MISSING: u8 = 0--pub type FlatEntry = {- path: mut bytes.Bytes- kind: mut u8- target: mut objid.Id-}--fn copy_id(id: objid.Id) objid.Id = trust {- val out: ref u8 = @alloc(32) as ref u8- @memcpy(out as ref void, id.ptr as ref void, 32)- return objid.id(out)-}--pub fn read_tree(handles: list[ref store.Handle], id: objid.Id) option[ref tree.Tree] = trust {- val body_opt = read.read_body(handles, id, types.TREE)- val body: mut bytes.Bytes = bytes.empty()- match body_opt {- some b => {- body = b- }- none => {- return none- }- }- val decoded = tree.decode(body)- match decoded {- ok t => {- t.body = body- return some t- }- err _ => {- files.free_buffer(body)- return none- }- }-}--pub fn find_name(t: ref tree.Tree, name: bytes.Bytes) i32 = trust {- val lo: mut usize = 0- val hi: mut usize = @len(t.entries)- for lo < hi {- val mid: usize = lo + (hi - lo) / 2- val e = @get(t.entries, mid)- val c: mut i64 = 0- if e is some entry {- c = bytes.Bytes.cmp(entry.name, name)- if c == 0 {- return mid as i32- }- }- if c < 0 {- lo = mid + 1- } else {- hi = mid- }- }- return -1-}--fn join_path(prefix: bytes.Bytes, name: bytes.Bytes) bytes.Bytes = trust {- if prefix.len == 0 {- return bytes.Bytes.dup(name)- }- val out: ref u8 = @alloc(prefix.len + 1 + name.len) as ref u8- @memcpy(out as ref void, prefix.ptr as ref void, prefix.len)- @store8(@ptradd(out, prefix.len as i64), 47)- @memcpy(- @ptradd(out, (prefix.len + 1) as i64) as ref void,- name.ptr as ref void,- name.len- )- return bytes.bytes(out, prefix.len + 1 + name.len)-}--fn new_flat(path: bytes.Bytes, kind: u8, target: objid.Id) ref FlatEntry = trust {- val e: mut ref FlatEntry = @alloc(@sizeof(FlatEntry)) as ref FlatEntry- e.path = path- e.kind = kind- e.target = copy_id(target)- return e-}--fn flatten_into(- handles: list[ref store.Handle],- tree_id: objid.Id,- prefix: bytes.Bytes,- out: mut list[ref FlatEntry],- depth: usize-) bool = trust {- if depth > 4096 {- return false- }- val t_opt = read_tree(handles, tree_id)- val t: mut ref tree.Tree = none- match t_opt {- some x => {- t = x- }- none => {- return false- }- }- val good: mut bool = true- for e in t.entries {- val path: bytes.Bytes = join_path(prefix, e.name)- if e.kind == tree.KIND_SUBTREE {- if !flatten_into(handles, e.target, path, out, depth + 1) {- files.free_buffer(path)- good = false- break- }- files.free_buffer(path)- } else {- @append(out, new_flat(path, e.kind, e.target))- }- }- tree.free_tree(t)- return good-}--fn entry_at(xs: list[ref FlatEntry], i: usize) ref FlatEntry = trust {- val o = @get(xs, i)- if o is some e {- return e- }- assert false- return none-}--fn merge_sort(- xs: mut list[ref FlatEntry],- lo: usize,- hi: usize,- tmp: mut list[ref FlatEntry]-) void = trust {- if hi - lo <= 1 {- return- }- val mid: usize = lo + (hi - lo) / 2- merge_sort(xs, lo, mid, tmp)- merge_sort(xs, mid, hi, tmp)- val i: mut usize = lo- val j: mut usize = mid- val k: mut usize = lo- for k < hi {- val take_left: mut bool = false- if i >= mid {- take_left = false- } elif j >= hi {- take_left = true- } else {- take_left = bytes.Bytes.cmp(entry_at(xs, i).path, entry_at(xs, j).path) <= 0- }- if take_left {- @set(tmp, k, entry_at(xs, i))- i++- } else {- @set(tmp, k, entry_at(xs, j))- j++- }- k++- }- val m: mut usize = lo- for m < hi {- @set(xs, m, entry_at(tmp, m))- m++- }-}--pub fn sort_flat(xs: mut list[ref FlatEntry]) void = trust {- val n: usize = @len(xs)- if n <= 1 {- return- }- val tmp: mut list[ref FlatEntry] = lists.new[ref FlatEntry]()- val i: mut usize = 0- for i < n {- @append(tmp, none)- i++- }- merge_sort(xs, 0, n, tmp)- @listfree(tmp)-}--/// Flatten a tree into path entries sorted by full path.-pub fn flatten(handles: list[ref store.Handle], tree_id: objid.Id) list[ref FlatEntry] = trust {- val out: mut list[ref FlatEntry] = lists.new[ref FlatEntry]()- if !flatten_into(handles, tree_id, bytes.empty(), out, 0) {- // Return what was collected; callers treat a short list as an error- // through `tree_conflicted` / direct read failures.- }- sort_flat(out)- return out-}--pub fn flatten_or_empty(- handles: list[ref store.Handle],- tree: option[objid.Id]-) list[ref FlatEntry] = trust {- if tree is some id {- return flatten(handles, id)- }- return lists.new[ref FlatEntry]()-}--pub fn lookup(entries: list[ref FlatEntry], path: bytes.Bytes) option[ref FlatEntry] = trust {- val lo: mut usize = 0- val hi: mut usize = @len(entries)- for lo < hi {- val mid: usize = lo + (hi - lo) / 2- val c: i64 = bytes.Bytes.cmp(entry_at(entries, mid).path, path)- if c == 0 {- return some entry_at(entries, mid)- }- if c < 0 {- lo = mid + 1- } else {- hi = mid- }- }- return none-}--fn conflicted_into(- handles: list[ref store.Handle],- tree_id: objid.Id,- depth: usize-) bool = trust {- if depth > 4096 {- return true- }- val t_opt = read_tree(handles, tree_id)- val t: mut ref tree.Tree = none- match t_opt {- some x => {- t = x- }- none => {- return true- }- }- val found: mut bool = false- for e in t.entries {- if e.kind == tree.KIND_CONFLICT {- found = true- break- }- if e.kind == tree.KIND_SUBTREE && conflicted_into(handles, e.target, depth + 1) {- found = true- break- }- }- tree.free_tree(t)- return found-}--pub fn conflicted(handles: list[ref store.Handle], tree_id: objid.Id) bool = trust {- return conflicted_into(handles, tree_id, 0)-}--pub fn free_flat(xs: list[ref FlatEntry]) void = trust {- for e in xs {- if e.path.ptr != none {- val pp: mut ref void = e.path.ptr as ref void- @free(pp)- }- if e.target.ptr != none {- val tp: mut ref void = e.target.ptr as ref void- @free(tp)- }- val ep: mut ref void = e as ref void- @free(ep)- }- @listfree(xs)-}--- a/src/src/object/types.sx+++ /dev/null@@ -1,40 +0,0 @@-/// 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-}--- a/src/src/object/view.sx+++ /dev/null@@ -1,403 +0,0 @@-/// 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++- }- 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++- }- 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++- }- 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++- }- 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++- }- 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++- }- 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++- }- 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++- }- 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)-}--- a/src/src/store/fsck.sx+++ /dev/null@@ -1,693 +0,0 @@-/// `vn fsck`: canonical-form, hash, referential-integrity, and op-log checks.--val str = use("std/string")-val stdio = use("std/stdio")-val msg = use("../core/msg.sx")-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")-val lazy = use("../git/lazy.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, text: str.StringView) void = {- ctx.errors++- trust msg.error_prefix()- trust stdio.eprint("fsck: {s}: {s}\n", {path, text})-}--fn report_id(ctx: mut Ctx, path: str.StringView, text: str.StringView, id: objid.Id) void = {- ctx.errors++- val hx: ref u8 = objid.Id.hex(id)- trust msg.error_prefix()- trust stdio.eprint("fsck: {s}: {s} {s}\n", {path, text, str.from_cstr(hx)})- val p: mut ref void = hx as ref void- trust @free(p)-}--fn warn(ctx: mut Ctx, path: str.StringView, text: str.StringView) void = {- ctx.warnings++- if ctx.verbose {- trust msg.warning_prefix()- trust stdio.eprint("fsck: {s}: {s}\n", {path, text})- }-}--fn format_ok(d: bytes.Bytes) bool = {- val expected: bytes.Bytes = bytes.bytes(c"veins-store 1", 13)- 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 .veins/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 .veins/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- }- if expected == types.BLOB && lazy.is_lazy(id) {- return true- }- 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++- }- 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++- }- @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++- }- i++- }-}--fn copy_id(id: objid.Id) objid.Id = trust {- val out: ref u8 = @alloc(32) as ref u8- @memcpy(out as ref void, id.ptr as ref void, 32)- return objid.id(out)-}--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, copy_id(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 {- msg.warning_prefix()- stdio.eprint("{d} warning(s)\n", {ctx.warnings})- }- if ctx.errors == 0 {- msg.info_prefix()- stdio.print("fsck: clean\n", {})- return 0- }- msg.error_prefix()- stdio.eprint("{d} error(s)\n", {ctx.errors})- return 1-}--- a/src/src/store/idmap.sx+++ /dev/null@@ -1,139 +0,0 @@-/// Membership set keyed by 32-byte veins object IDs.--val bytes = use("../core/bytes.sx")--pub val ID_LEN: usize = 32-pub val SLOT_LEN: usize = 40--pub type IdSet = {- slots: mut ref u8- cap: mut usize- len: mut usize-}--fn round_cap(n: usize) usize = {- val c: mut usize = 16- for c < n {- c = c * 2- }- return c-}--fn key_ptr(set: IdSet, i: usize) ref u8 = trust {- return @ptradd(set.slots, (i * SLOT_LEN + 1) as i64)-}--fn used_at(set: IdSet, i: usize) bool = trust {- return @load8(@ptradd(set.slots, (i * SLOT_LEN) as i64)) != 0-}--fn set_used(set: IdSet, i: usize) void = trust {- @store8(@ptradd(set.slots, (i * SLOT_LEN) as i64), 1)-}--fn hash_id(id: bytes.Bytes) u64 = {- val h: mut u64 = 1469598103934665603- val k: mut usize = 0- for k < ID_LEN {- h = (h ^ (bytes.Bytes.at(id, k) as u64)) * 1099511628211- k++- }- return h-}--fn slot_eql(set: IdSet, i: usize, id: bytes.Bytes) bool = trust {- return bytes.Bytes.eql(bytes.bytes(key_ptr(set, i), ID_LEN), id)-}--fn copy_key(set: IdSet, i: usize, id: bytes.Bytes) void = trust {- @memcpy(key_ptr(set, i) as ref void, id.ptr as ref void, ID_LEN)-}--pub fn new(initial: usize) IdSet = trust {- val cap: usize = round_cap(initial)- val p: ref u8 = @alloc(cap * SLOT_LEN) as ref u8- @memset(p as ref void, 0, cap * SLOT_LEN)- return IdSet{slots: p, cap: cap, len: 0}-}--pub fn free(set: mut IdSet) void = trust {- if set.slots != none {- @free(set.slots as ref void)- }- set.slots = none- set.cap = 0- set.len = 0-}--fn grow(set: mut IdSet) void = trust {- val old_slots: mut ref u8 = set.slots- val old_cap: usize = set.cap- val new_cap: usize = old_cap * 2- val p: ref u8 = @alloc(new_cap * SLOT_LEN) as ref u8- @memset(p as ref void, 0, new_cap * SLOT_LEN)- set.slots = p- set.cap = new_cap- set.len = 0- val i: mut usize = 0- for i < old_cap {- if @load8(@ptradd(old_slots, (i * SLOT_LEN) as i64)) != 0 {- val id: bytes.Bytes = bytes.bytes(- @ptradd(old_slots, (i * SLOT_LEN + 1) as i64),- ID_LEN- )- val _ = insert_existing(set, id)- }- i++- }- @free(old_slots as ref void)-}--fn insert_existing(set: mut IdSet, id: bytes.Bytes) bool = trust {- val mask: usize = set.cap - 1- val idx: mut usize = (hash_id(id) as usize) & mask- for {- if !used_at(set, idx) {- set_used(set, idx)- copy_key(set, idx, id)- set.len++- return true- }- if slot_eql(set, idx, id) {- return false- }- idx = (idx + 1) & mask- }- return false-}--/// Insert `id`. Returns true when it was not already present.-pub fn put(set: mut IdSet, id: bytes.Bytes) bool = trust {- pre {- id_len: id.len == ID_LEN- }- if (set.len + 1) * 10 >= set.cap * 7 {- grow(set)- }- return insert_existing(set, id)-}--pub fn contains(set: IdSet, id: bytes.Bytes) bool = trust {- pre {- id_len: id.len == ID_LEN- }- if set.cap == 0 {- return false- }- val mask: usize = set.cap - 1- val idx: mut usize = (hash_id(id) as usize) & mask- for {- if !used_at(set, idx) {- return false- }- if slot_eql(set, idx, id) {- return true- }- idx = (idx + 1) & mask- }- return false-}--- a/src/src/store/index.sx+++ /dev/null@@ -1,222 +0,0 @@-/// 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++- }-- 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++- }- 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++- }- 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++- }- 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-}--- a/src/src/store/layout.sx+++ /dev/null@@ -1,234 +0,0 @@-/// 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 = 13--fn format_text() bytes.Bytes = {- return bytes.bytes(c"veins-store 1", 13)-}--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 `.veins/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)), ".veins/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--- }- 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 veins_dir(r: Repo) str.StringView = {- return files.join(root_view(r), ".veins")-}--pub fn packs_dir(r: Repo) str.StringView = {- return files.join(root_view(r), ".veins/store/packs")-}--pub fn tmp_dir(r: Repo) str.StringView = {- return files.join(root_view(r), ".veins/store/tmp")-}--pub fn op_heads_dir(r: Repo) str.StringView = {- return files.join(root_view(r), ".veins/op-heads")-}--pub fn git_dir(r: Repo) str.StringView = {- return files.join(root_view(r), ".veins/git")-}--pub fn git_map_dir(r: Repo) str.StringView = {- return files.join(root_view(r), ".veins/git-map")-}--pub fn raw_dir(r: Repo) str.StringView = {- return files.join(root_view(r), ".veins/git-map/raw")-}--pub fn working_copy_dir(r: Repo) str.StringView = {- return files.join(root_view(r), ".veins/working-copy")-}--pub fn config_path(r: Repo) str.StringView = {- return files.join(root_view(r), ".veins/config")-}--pub fn format_path(r: Repo) str.StringView = {- return files.join(root_view(r), ".veins/format")-}--fn mkdirs_under(r: Repo, sub: str.StringView) bool = {- val p: str.StringView = files.join(root_view(r), sub)- if files.exists_dir(p) {- files.free_path(p)- return true- }- val created: bool = files.mkdir_all(p)- files.free_path(p)- return created-}--fn migrate_dir(r: Repo, old_sub: str.StringView, new_sub: str.StringView) bool = {- val oldp: str.StringView = files.join(root_view(r), old_sub)- val newp: str.StringView = files.join(root_view(r), new_sub)- val old_exists: bool = files.exists_dir(oldp)- val new_exists: bool = files.exists_dir(newp)- val moved: mut bool = true- if old_exists && !new_exists {- moved = files.rename_path(oldp, newp)- }- files.free_path(oldp)- files.free_path(newp)- return moved-}--fn ensure_layout(r: Repo) bool = {- if !migrate_dir(r, ".veins/op_heads", ".veins/op-heads") {- return false- }- if !migrate_dir(r, ".veins/working_copy", ".veins/working-copy") {- return false- }- if !mkdirs_under(r, ".veins") {- return false- }- if !mkdirs_under(r, ".veins/store") {- return false- }- if !mkdirs_under(r, ".veins/store/packs") {- return false- }- if !mkdirs_under(r, ".veins/store/tmp") {- return false- }- if !mkdirs_under(r, ".veins/op-heads") {- return false- }- if !mkdirs_under(r, ".veins/git-map") {- return false- }- if !mkdirs_under(r, ".veins/git-map/raw") {- return false- }- if !mkdirs_under(r, ".veins/working-copy") {- return false- }- if !mkdirs_under(r, ".veins/resolutions") {- return false- }- return true-}--/// 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)- val had_format: bool = files.exists_file(format)- if had_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- }- } else {- free_repo(repo)- return err 3- }- } else {- files.free_path(format)- }-- if !ensure_layout(repo) {- free_repo(repo)- return err 4- }-- if !had_format {- 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-}--- a/src/src/store/pack.sx+++ /dev/null@@ -1,363 +0,0 @@-/// 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++- }- 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- )- trust 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)-}--- a/src/src/store/records.sx+++ /dev/null@@ -1,117 +0,0 @@-/// Metadata kept per object while a pack and its index are built.--val objid = use("../object/id.sx")-val lists = use("../core/lists.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 ref_at(xs: list[ref RecordMeta], i: usize) ref RecordMeta = {- val o = @get(xs, i)- if o is some r {- return r- }- assert false- return none-}--fn merge_run(- src: list[ref RecordMeta],- dst: mut list[ref RecordMeta],- left: usize,- mid: usize,- right: usize-) void = {- val i: mut usize = left- val j: mut usize = mid- val k: mut usize = left- for k < right {- val take_left: mut bool = false- if i >= mid {- take_left = false- } elif j >= right {- take_left = true- } else {- take_left = objid.Id.cmp(ref_at(src, i).id, ref_at(src, j).id) <= 0- }- if take_left {- @set(dst, k, ref_at(src, i))- i++- } else {- @set(dst, k, ref_at(src, j))- j++- }- k++- }-}--/// Stable bottom-up merge sort by object ID.-pub fn sort_by_id(records: mut list[ref RecordMeta]) void = trust {- val n: usize = @len(records)- if n < 2 {- return- }- val src: mut list[ref RecordMeta] = lists.new[ref RecordMeta]()- val dst: mut list[ref RecordMeta] = lists.new[ref RecordMeta]()- val i: mut usize = 0- for i < n {- val o = @get(records, i)- if o is some r {- @append(src, r)- @append(dst, r)- } else {- @append(src, none)- @append(dst, none)- }- i++- }- val mut_a: mut list[ref RecordMeta] = src- val mut_b: mut list[ref RecordMeta] = dst- val width: mut usize = 1- for width < n {- val left: mut usize = 0- for left < n {- val mid: mut usize = n- if left + width < n {- mid = left + width- }- val right: mut usize = n- if left + 2 * width < n {- right = left + 2 * width- }- merge_run(mut_a, mut_b, left, mid, right)- left = left + 2 * width- }- val tmp: list[ref RecordMeta] = mut_a- mut_a = mut_b- mut_b = tmp- width = width * 2- }- val j: mut usize = 0- for j < n {- @set(records, j, ref_at(mut_a, j))- j++- }- @listfree(src)- @listfree(dst)-}--- a/src/src/store/state.sx+++ /dev/null@@ -1,265 +0,0 @@-/// Read the current operation/view state and advance operation heads.--val str = use("std/string")-val bytes = use("../core/bytes.sx")-val lists = use("../core/lists.sx")-val objid = use("../object/id.sx")-val types = use("../object/types.sx")-val operation = use("../object/operation.sx")-val view = use("../object/view.sx")-val store = use("../store/store.sx")-val layout = use("../store/layout.sx")-val files = use("../io/files.sx")-val native = use("../io/native.sx")--pub fn read_body(- handles: list[ref store.Handle],- id: objid.Id,- expected: u8-) option[bytes.Bytes] = trust {- val loc: mut store.Loc = store.Loc{pack_index: 0, record_index: 0, kind: 0}- if !store.find_handles(handles, id, loc) {- return none- }- if loc.kind != expected {- return none- }- val body_opt = store.get_handles(handles, loc)- val body: mut bytes.Bytes = bytes.empty()- match body_opt {- ok b => {- body = b- }- err _ => {- return none- }- }- val computed: objid.Id = objid.object_id(expected, body)- val same: bool = objid.Id.eql(computed, id)- if computed.ptr != none {- val cp: mut ref void = computed.ptr as ref void- @free(cp)- }- if !same {- files.free_buffer(body)- return none- }- return some body-}--pub fn read_view(handles: list[ref store.Handle], id: objid.Id) option[ref view.View] = trust {- val body_opt = read_body(handles, id, types.VIEW)- val body: mut bytes.Bytes = bytes.empty()- match body_opt {- some b => {- body = b- }- none => {- return none- }- }- val decoded = view.decode(body)- match decoded {- ok v => {- return some v- }- err _ => {- files.free_buffer(body)- return none- }- }-}--pub fn read_operation(- handles: list[ref store.Handle],- id: objid.Id-) option[ref operation.Operation] = trust {- val body_opt = read_body(handles, id, types.OPERATION)- val body: mut bytes.Bytes = bytes.empty()- match body_opt {- some b => {- body = b- }- none => {- return none- }- }- val decoded = operation.decode(body)- match decoded {- ok op => {- return some op- }- err _ => {- files.free_buffer(body)- return none- }- }-}--fn parse_head_name(name: ref u8) option[objid.Id] = trust {- val n: i64 = @strlen(name)- if n != 64 {- return none- }- val raw: ref u8 = @alloc(32) as ref u8- val i: mut usize = 0- for i < 32 {- val hex: bytes.Bytes = bytes.bytes(name, 64)- val hi_c: u8 = bytes.Bytes.at(hex, i * 2)- val lo_c: u8 = bytes.Bytes.at(hex, i * 2 + 1)- val hi: mut i32 = -1- val lo: mut i32 = -1- if hi_c >= 48 && hi_c <= 57 {- hi = (hi_c - 48) as i32- } elif hi_c >= 97 && hi_c <= 102 {- hi = (hi_c - 87) as i32- } elif hi_c >= 65 && hi_c <= 70 {- hi = (hi_c - 55) as i32- }- if lo_c >= 48 && lo_c <= 57 {- lo = (lo_c - 48) as i32- } elif lo_c >= 97 && lo_c <= 102 {- lo = (lo_c - 87) as i32- } elif lo_c >= 65 && lo_c <= 70 {- lo = (lo_c - 55) as i32- }- if hi < 0 || lo < 0 {- @free(raw as ref void)- return none- }- @store8(@ptradd(raw, i as i64), ((hi * 16 + lo) as u8))- i++- }- return some objid.id(raw)-}--fn sort_ids(ids: mut list[objid.Id]) void = trust {- val n: usize = @len(ids)- val i: mut usize = 1- for i < n {- val cur = @get(ids, i)- val cid: mut objid.Id = objid.id_none()- if cur is some v {- cid = v- }- val j: mut usize = i- for j > 0 {- val prev_opt = @get(ids, j - 1)- val prev: mut objid.Id = objid.id_none()- if prev_opt is some v2 {- prev = v2- }- if objid.Id.cmp(prev, cid) <= 0 {- break- }- @set(ids, j, prev)- j--- }- @set(ids, j, cid)- i++- }-}--pub fn heads(repo: layout.Repo) list[objid.Id] = trust {- val out: mut list[objid.Id] = lists.new[objid.Id]()- val dir: str.StringView = layout.op_heads_dir(repo)- if !files.exists_dir(dir) {- files.free_path(dir)- return out- }- val names: list[ref u8] = files.list_dir(dir)- for n in names {- val parsed = parse_head_name(n)- if parsed is some id {- @append(out, id)- }- }- files.free_names(names)- files.free_path(dir)- sort_ids(out)- return out-}--pub fn current_view(- repo: layout.Repo,- handles: list[ref store.Handle]-) option[ref view.View] = trust {- val hs: list[objid.Id] = heads(repo)- if @len(hs) == 0 {- return none- }- val first = @get(hs, 0)- val op_id: mut objid.Id = objid.id_none()- if first is some v {- op_id = v- }- val op_opt = read_operation(handles, op_id)- match op_opt {- some op => {- val v_opt = read_view(handles, op.view)- operation.free_operation(op)- for h in hs {- if h.ptr != none {- val hp: mut ref void = h.ptr as ref void- @free(hp)- }- }- @listfree(hs)- return v_opt- }- none => {- for h in hs {- if h.ptr != none {- val hp2: mut ref void = h.ptr as ref void- @free(hp2)- }- }- @listfree(hs)- return none- }- }-}--pub fn empty_view() ref view.View = trust {- val v: mut ref view.View = @alloc(@sizeof(view.View)) as ref view.View- v.heads = lists.new[objid.Id]()- v.bookmarks = lists.new[ref view.Bookmark]()- v.tags = lists.new[ref view.TagRef]()- v.remote_refs = lists.new[ref view.RemoteRef]()- v.working_copies = lists.new[ref view.WorkspaceRef]()- return v-}--pub fn head_name(id: objid.Id) ref u8 = trust {- return objid.Id.hex(id)-}--pub fn write_head(repo: layout.Repo, id: objid.Id) bool = trust {- val hex: ref u8 = head_name(id)- val dir: str.StringView = layout.op_heads_dir(repo)- val name: str.StringView = str.from_cstr(hex)- val final: str.StringView = files.join(dir, name)- val tmpd: str.StringView = layout.tmp_dir(repo)- val tmpname: str.StringView = files.with_suffix(name, str.from_cstr(c".tmp"))- val tmp: str.StringView = files.join(tmpd, tmpname)- val success: bool = native.write_atomic(tmp, final, tmpd, dir, bytes.empty())- files.free_path(dir)- files.free_path(tmpd)- files.free_path(final)- files.free_path(tmpname)- files.free_path(tmp)- @free(hex as ref void)- return success-}--pub fn delete_head(repo: layout.Repo, id: objid.Id) bool = trust {- val hex: ref u8 = head_name(id)- val dir: str.StringView = layout.op_heads_dir(repo)- val name: str.StringView = str.from_cstr(hex)- val path: str.StringView = files.join(dir, name)- val success: bool = files.delete(path)- files.free_path(dir)- files.free_path(path)- @free(hex as ref void)- return success-}--- a/src/src/store/store.sx+++ /dev/null@@ -1,312 +0,0 @@-/// 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++- }- 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++- }- 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-}--- a/src/src/store/txn.sx+++ /dev/null@@ -1,476 +0,0 @@-/// Operation transactions: load the current view, append objects and a new-/// operation to a single pack, then advance the operation heads.--val stdio = use("std/stdio")-val msg = use("../core/msg.sx")-val os = use("std/os")-val time = use("std/time")-val bytes = use("../core/bytes.sx")-val lists = use("../core/lists.sx")-val prim = use("../core/primitives.sx")-val objid = use("../object/id.sx")-val types = use("../object/types.sx")-val operation = use("../object/operation.sx")-val view = use("../object/view.sx")-val writer = use("../store/writer.sx")-val store = use("../store/store.sx")-val state = use("../store/state.sx")-val layout = use("../store/layout.sx")--pub type Txn = {- repo: mut layout.Repo- writer: mut ref writer.Writer- view: mut ref view.View- parents: mut list[objid.Id]- start_ms: mut i64-}--fn copy_id(id: objid.Id) objid.Id = trust {- val out: ref u8 = @alloc(32) as ref u8- @memcpy(out as ref void, id.ptr as ref void, 32)- return objid.id(out)-}--fn free_ids(ids: list[objid.Id]) void = trust {- for id in ids {- if id.ptr != none {- val p: mut ref void = id.ptr as ref void- @free(p)- }- }- @listfree(ids)-}--fn same_id(a: objid.Id, b: objid.Id) bool = trust {- return objid.Id.eql(a, b)-}--fn contains_id(xs: list[objid.Id], id: objid.Id) bool = trust {- for x in xs {- if same_id(x, id) {- return true- }- }- return false-}--fn add_unique(xs: mut list[objid.Id], id: objid.Id) void = trust {- if !contains_id(xs, id) {- @append(xs, copy_id(id))- }-}--fn clone_targets(ts: view.TargetSet) view.TargetSet = trust {- val out: mut view.TargetSet = view.empty_target_set()- for a in ts.adds {- @append(out.adds, copy_id(a))- }- for r in ts.removes {- @append(out.removes, copy_id(r))- }- return out-}--fn clone_bookmark(bm: ref view.Bookmark) ref view.Bookmark = trust {- val b: mut ref view.Bookmark = @alloc(@sizeof(view.Bookmark)) as ref view.Bookmark- b.name = bytes.Bytes.dup(bm.name)- b.targets = clone_targets(bm.targets)- return b-}--fn clone_tag(t: ref view.TagRef) ref view.TagRef = trust {- val out: mut ref view.TagRef = @alloc(@sizeof(view.TagRef)) as ref view.TagRef- out.name = bytes.Bytes.dup(t.name)- out.target = copy_id(t.target)- return out-}--fn clone_workspace(w: ref view.WorkspaceRef) ref view.WorkspaceRef = trust {- val out: mut ref view.WorkspaceRef = @alloc(@sizeof(view.WorkspaceRef)) as ref view.WorkspaceRef- out.workspace = bytes.Bytes.dup(w.workspace)- out.target = copy_id(w.target)- return out-}--fn find_bookmark(v: ref view.View, name: bytes.Bytes) i32 = trust {- val i: mut usize = 0- for i < @len(v.bookmarks) {- val o = @get(v.bookmarks, i)- if o is some bm {- if bytes.Bytes.eql(bm.name, name) {- return i as i32- }- }- i++- }- return -1-}--fn find_tag(v: ref view.View, name: bytes.Bytes) i32 = trust {- val i: mut usize = 0- for i < @len(v.tags) {- val o = @get(v.tags, i)- if o is some t {- if bytes.Bytes.eql(t.name, name) {- return i as i32- }- }- i++- }- return -1-}--fn find_workspace(v: ref view.View, name: bytes.Bytes) i32 = trust {- val i: mut usize = 0- for i < @len(v.working_copies) {- val o = @get(v.working_copies, i)- if o is some w {- if bytes.Bytes.eql(w.workspace, name) {- return i as i32- }- }- i++- }- return -1-}--fn conflict_targets(a: objid.Id, b: objid.Id) view.TargetSet = trust {- val ts: mut view.TargetSet = view.empty_target_set()- @append(ts.adds, copy_id(a))- @append(ts.adds, copy_id(b))- @append(ts.removes, objid.id(none))- return ts-}--fn merge_view_into(dst: mut ref view.View, src: ref view.View) void = trust {- for h in src.heads {- add_unique(dst.heads, h)- }- for bm in src.bookmarks {- val idx: i32 = find_bookmark(dst, bm.name)- if idx < 0 {- @append(dst.bookmarks, clone_bookmark(bm))- } else {- val existing = @get(dst.bookmarks, idx as usize)- if existing is some e {- val a: mut objid.Id = objid.id_none()- val b: mut objid.Id = objid.id_none()- if @len(e.targets.adds) > 0 {- val o = @get(e.targets.adds, 0)- if o is some id {- a = id- }- }- if @len(bm.targets.adds) > 0 {- val o2 = @get(bm.targets.adds, 0)- if o2 is some id2 {- b = id2- }- }- if !same_id(a, b) || @len(e.targets.adds) != @len(bm.targets.adds) {- @listfree(e.targets.adds)- @listfree(e.targets.removes)- e.targets = conflict_targets(a, b)- }- }- }- }- for t in src.tags {- if find_tag(dst, t.name) < 0 {- @append(dst.tags, clone_tag(t))- }- }- for w in src.working_copies {- if find_workspace(dst, w.workspace) < 0 {- @append(dst.working_copies, clone_workspace(w))- }- }-}--fn sort_bookmarks(xs: mut list[ref view.Bookmark]) void = trust {- val i: mut usize = 1- for i < @len(xs) {- val cur = @get(xs, i)- val c: mut ref view.Bookmark = none- if cur is some v {- c = v- }- val j: mut usize = i- for j > 0 {- val prev_opt = @get(xs, j - 1)- val prev: mut ref view.Bookmark = none- if prev_opt is some v2 {- prev = v2- }- if bytes.Bytes.cmp(prev.name, c.name) <= 0 {- break- }- @set(xs, j, prev)- j--- }- @set(xs, j, c)- i++- }-}--fn sort_tags(xs: mut list[ref view.TagRef]) void = trust {- val i: mut usize = 1- for i < @len(xs) {- val cur = @get(xs, i)- val c: mut ref view.TagRef = none- if cur is some v {- c = v- }- val j: mut usize = i- for j > 0 {- val prev_opt = @get(xs, j - 1)- val prev: mut ref view.TagRef = none- if prev_opt is some v2 {- prev = v2- }- if bytes.Bytes.cmp(prev.name, c.name) <= 0 {- break- }- @set(xs, j, prev)- j--- }- @set(xs, j, c)- i++- }-}--fn sort_workspaces(xs: mut list[ref view.WorkspaceRef]) void = trust {- val i: mut usize = 1- for i < @len(xs) {- val cur = @get(xs, i)- val c: mut ref view.WorkspaceRef = none- if cur is some v {- c = v- }- val j: mut usize = i- for j > 0 {- val prev_opt = @get(xs, j - 1)- val prev: mut ref view.WorkspaceRef = none- if prev_opt is some v2 {- prev = v2- }- if bytes.Bytes.cmp(prev.workspace, c.workspace) <= 0 {- break- }- @set(xs, j, prev)- j--- }- @set(xs, j, c)- i++- }-}--fn load_view_for_head(- handles: list[ref store.Handle],- id: objid.Id-) option[ref view.View] = trust {- val op_opt = state.read_operation(handles, id)- val op: mut ref operation.Operation = none- match op_opt {- some o => {- op = o- }- none => {- return none- }- }- val view_id: objid.Id = copy_id(op.view)- operation.free_operation(op)- val v_opt = state.read_view(handles, view_id)- if view_id.ptr != none {- val vp: mut ref void = view_id.ptr as ref void- @free(vp)- }- return v_opt-}--pub fn begin(repo: layout.Repo) option[ref Txn] = trust {- val heads: list[objid.Id] = state.heads(repo)- val st: store.Store = store.open_all(repo)- val v: mut ref view.View = none- if @len(heads) == 0 {- v = state.empty_view()- } elif @len(heads) == 1 {- val only = @get(heads, 0)- val id: mut objid.Id = objid.id_none()- if only is some x {- id = x- }- val loaded = load_view_for_head(st.handles, id)- match loaded {- some x => {- v = x- }- none => {- store.close(st)- free_ids(heads)- return none- }- }- } else {- val first = @get(heads, 0)- val first_id: mut objid.Id = objid.id_none()- if first is some x {- first_id = x- }- val base = load_view_for_head(st.handles, first_id)- val base_view: mut ref view.View = none- match base {- some x => {- base_view = x- }- none => {- store.close(st)- free_ids(heads)- return none- }- }- val i: mut usize = 1- for i < @len(heads) {- val o = @get(heads, i)- val hid: mut objid.Id = objid.id_none()- if o is some x {- hid = x- }- val extra = load_view_for_head(st.handles, hid)- if extra is some ev {- merge_view_into(base_view, ev)- view.free_view(ev)- }- i++- }- add_unique(base_view.heads, first_id)- v = base_view- }- store.close(st)- sort_bookmarks(v.bookmarks)- sort_tags(v.tags)- sort_workspaces(v.working_copies)- val w_opt = writer.open(repo)- val w: mut ref writer.Writer = none- match w_opt {- some x => {- w = x- }- none => {- view.free_view(v)- free_ids(heads)- return none- }- }- val tx: mut ref Txn = @alloc(@sizeof(Txn)) as ref Txn- tx.repo = repo- tx.writer = w- tx.view = v- tx.parents = heads- tx.start_ms = time.unix_now_millis()- return some tx-}--pub fn add_object(tx: mut ref Txn, kind: u8, body: bytes.Bytes) objid.Id = trust {- return writer.add(tx.writer, kind, body)-}--pub fn add_known(tx: mut ref Txn, kind: u8, id: objid.Id, body: bytes.Bytes) objid.Id = trust {- return writer.add_known(tx.writer, kind, id, body)-}--fn host_from_env() bytes.Bytes = trust {- val h = os.env(c"HOSTNAME")- match h {- some v => {- return bytes.Bytes.dup(bytes.from_cstr(v))- }- none => {- return bytes.Bytes.dup(bytes.bytes(c"localhost", 9))- }- }-}--fn user_from_env() bytes.Bytes = trust {- val u = os.env(c"USER")- match u {- some v => {- return bytes.Bytes.dup(bytes.from_cstr(v))- }- none => {- return bytes.Bytes.dup(bytes.bytes(c"unknown", 7))- }- }-}--fn free_txn(tx: mut ref Txn) void = trust {- if tx.view != none {- view.free_view(tx.view)- }- free_ids(tx.parents)- @free(tx as ref void)-}--pub fn abort(tx: mut ref Txn) void = trust {- writer.abort(tx.writer)- free_txn(tx)-}--/// Encode the view, write an operation, and advance the heads.-pub fn finish(tx: mut ref Txn, description: bytes.Bytes) i32 = trust {- val view_body: bytes.Bytes = view.encode(tx.view)- val view_id: objid.Id = writer.add(tx.writer, types.VIEW, view_body)- val now: i64 = time.unix_now_millis()- val hostname: bytes.Bytes = host_from_env()- val username: bytes.Bytes = user_from_env()- val tags: mut list[ref prim.KeyValue] = lists.new[ref prim.KeyValue]()- val kv: mut ref prim.KeyValue = @alloc(@sizeof(prim.KeyValue)) as ref prim.KeyValue- kv.key = bytes.bytes(c"command", 7)- kv.value = bytes.Bytes.dup(description)- @append(tags, kv)- val op: mut ref operation.Operation = @alloc(@sizeof(operation.Operation)) as ref operation.Operation- op.parents = lists.new[objid.Id]()- for p in tx.parents {- @append(op.parents, copy_id(p))- }- op.view = view_id- op.start = prim.TimeMs{ms: tx.start_ms, tz_min: 0}- op.end = prim.TimeMs{ms: now, tz_min: 0}- op.hostname = hostname- op.username = username- op.description = bytes.Bytes.dup(description)- op.tags = tags- val op_body: bytes.Bytes = operation.encode(op)- val op_id: objid.Id = writer.add(tx.writer, types.OPERATION, op_body)- operation.free_operation(op)-- val wrote: bool = writer.finish(tx.writer)- if !wrote {- msg.error_prefix()- stdio.eprint("failed to write object pack\n", {})- free_txn(tx)- return 1- }- val head_ok: bool = state.write_head(tx.repo, op_id)- if head_ok {- for p in tx.parents {- if !objid.Id.is_none(p) {- val _ = state.delete_head(tx.repo, p)- }- }- }- if view_id.ptr != none {- val vp: mut ref void = view_id.ptr as ref void- @free(vp)- }- if op_id.ptr != none {- val opp: mut ref void = op_id.ptr as ref void- @free(opp)- }- free_txn(tx)- if !head_ok {- return 1- }- return 0-}--- a/src/src/store/viewops.sx+++ /dev/null@@ -1,166 +0,0 @@-/// Small view mutations shared by working-copy and operation commands.--val bytes = use("../core/bytes.sx")-val lists = use("../core/lists.sx")-val objid = use("../object/id.sx")-val view = use("../object/view.sx")--pub fn copy_id(id: objid.Id) objid.Id = trust {- val out: ref u8 = @alloc(32) as ref u8- @memcpy(out as ref void, id.ptr as ref void, 32)- return objid.id(out)-}--pub fn same(a: objid.Id, b: objid.Id) bool = trust {- return objid.Id.eql(a, b)-}--pub fn contains(xs: list[objid.Id], id: objid.Id) bool = trust {- for x in xs {- if same(x, id) {- return true- }- }- return false-}--pub fn add_unique(xs: mut list[objid.Id], id: objid.Id) void = trust {- if !contains(xs, id) {- @append(xs, copy_id(id))- }-}--pub fn workspace_name() bytes.Bytes = trust {- return bytes.bytes(c"default", 7)-}--pub fn working_copy(v: ref view.View) option[objid.Id] = trust {- val name: bytes.Bytes = workspace_name()- for w in v.working_copies {- if bytes.Bytes.eql(w.workspace, name) {- return some copy_id(w.target)- }- }- return none-}--pub fn set_workspace(v: mut ref view.View, id: objid.Id) void = trust {- val name: bytes.Bytes = workspace_name()- val i: mut usize = 0- for i < @len(v.working_copies) {- val o = @get(v.working_copies, i)- if o is some w {- if bytes.Bytes.eql(w.workspace, name) {- w.target = copy_id(id)- return- }- }- i++- }- val w2: mut ref view.WorkspaceRef = @alloc(@sizeof(view.WorkspaceRef)) as ref view.WorkspaceRef- w2.workspace = bytes.Bytes.dup(name)- w2.target = copy_id(id)- @append(v.working_copies, w2)- sort_workspaces(v.working_copies)-}--pub fn remove_head(v: mut ref view.View, id: objid.Id) void = trust {- val i: mut usize = 0- for i < @len(v.heads) {- val o = @get(v.heads, i)- if o is some h {- if same(h, id) {- @remove(v.heads, i)- return- }- }- i++- }-}--fn sort_heads(xs: mut list[objid.Id]) void = trust {- val i: mut usize = 1- for i < @len(xs) {- val cur = @get(xs, i)- val c: mut objid.Id = objid.id_none()- if cur is some v {- c = v- }- val j: mut usize = i- for j > 0 {- val prev_opt = @get(xs, j - 1)- val prev: mut objid.Id = objid.id_none()- if prev_opt is some v2 {- prev = v2- }- if objid.Id.cmp(prev, c) <= 0 {- break- }- @set(xs, j, prev)- j--- }- @set(xs, j, c)- i++- }-}--pub fn rebuild_heads(v: mut ref view.View) void = trust {- for bm in v.bookmarks {- for id in bm.targets.adds {- add_unique(v.heads, id)- }- }- for t in v.tags {- add_unique(v.heads, t.target)- }- for w in v.working_copies {- add_unique(v.heads, w.target)- }- sort_heads(v.heads)-}--pub fn bookmark_names(v: ref view.View, id: objid.Id) list[bytes.Bytes] = trust {- val out: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()- for bm in v.bookmarks {- if contains(bm.targets.adds, id) {- @append(out, bm.name)- }- }- return out-}--pub fn tag_names(v: ref view.View, id: objid.Id) list[bytes.Bytes] = trust {- val out: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()- for t in v.tags {- if same(t.target, id) {- @append(out, t.name)- }- }- return out-}--pub fn sort_workspaces(xs: mut list[ref view.WorkspaceRef]) void = trust {- val i: mut usize = 1- for i < @len(xs) {- val cur = @get(xs, i)- val c: mut ref view.WorkspaceRef = none- if cur is some v {- c = v- }- val j: mut usize = i- for j > 0 {- val prev_opt = @get(xs, j - 1)- val prev: mut ref view.WorkspaceRef = none- if prev_opt is some v2 {- prev = v2- }- if bytes.Bytes.cmp(prev.workspace, c.workspace) <= 0 {- break- }- @set(xs, j, prev)- j--- }- @set(xs, j, c)- i++- }-}--- a/src/src/store/writer.sx+++ /dev/null@@ -1,456 +0,0 @@-/// Streaming pack writer used by the git importer.-///-/// Records are appended to a temporary file as they are produced. At finish,-/// the header count is patched, the pack trailer is hashed by streaming over-/// the file, and the index is written from the collected record metadata.--val str = use("std/string")-val time = use("std/time")-val allocators = use("std/allocators")-val thread = use("std/thread")-val bytes = use("../core/bytes.sx")-val buf = use("../core/buf.sx")-val lists = use("../core/lists.sx")-val objid = use("../object/id.sx")-val records = use("records.sx")-val idmap = use("idmap.sx")-val index = use("index.sx")-val zstd = use("zstd.sx")-val layout = use("../store/layout.sx")-val files = use("../io/files.sx")-val native = use("../io/native.sx")-val b3 = use("../crypto/blake3.sx")--extern (C) fn sysconf(name: i32) i64 = "sysconf"--type PendingRecord = {- id: mut objid.Id- kind: mut u8- body: mut bytes.Bytes- stored: mut bytes.Bytes- comp: mut u8-}--type CompressJob = {- items: mut list[ref PendingRecord]- start: mut usize- step: mut usize-}--pub type Writer = {- tmp_path: mut str.StringView- tmp_dir: mut str.StringView- packs_dir: mut str.StringView- fd: mut i32- count: mut usize- offset: mut u64- metas: mut list[ref records.RecordMeta]- items: mut list[ref PendingRecord]- pending_bytes: mut usize- failed: mut bool- seen: mut idmap.IdSet-}--fn worker_count() usize = trust {- when linux {- val n: i64 = sysconf(84)- if n > 0 {- return n as usize- }- }- when macos {- val n2: i64 = sysconf(58)- if n2 > 0 {- return n2 as usize- }- }- return 4-}--fn free_items(items: list[ref PendingRecord]) void = trust {- for r in items {- if r.body.ptr != none {- val bp: mut ref void = r.body.ptr as ref void- @free(bp)- }- if r.comp == 1 && r.stored.ptr != none {- val sp: mut ref void = r.stored.ptr as ref void- @free(sp)- }- if r.id.ptr != none {- val ip: mut ref void = r.id.ptr as ref void- @free(ip)- }- val rp: mut ref void = r as ref void- @free(rp)- }- @listfree(items)-}--fn compress_worker(arg: ref void) ref void = trust {- val job: ref CompressJob = arg as ref CompressJob- val i: mut usize = job.start- for i < @len(job.items) {- val item = @get(job.items, i)- if item is some r {- val compressed: bytes.Bytes = zstd.compress(r.body, zstd.DEFAULT_LEVEL)- if compressed.len > 0 {- r.comp = 1- r.stored = compressed- } else {- r.comp = 0- r.stored = r.body- }- }- i = i + job.step- }- return none-}--fn compress_items(items: list[ref PendingRecord]) void = trust {- val n: usize = @len(items)- if n == 0 {- return- }- val workers: mut usize = worker_count()- if workers < 1 {- workers = 1- }- if workers > n {- workers = n- }- val ac: allocators.HeapAllocator = @zeroed- val thread_refs: mut list[ref void] = lists.new[ref void]()- val jobs: mut list[ref CompressJob] = lists.new[ref CompressJob]()- val w: mut usize = 0- for w < workers {- val job: mut ref CompressJob = @alloc(@sizeof(CompressJob)) as ref CompressJob- job.items = items- job.start = w- job.step = workers- @append(jobs, job)- val tr = thread.Thread.new[allocators.HeapAllocator](ac, compress_worker, job as ref void)- match tr {- ok t => {- @append(thread_refs, t)- }- err _ => {- compress_worker(job as ref void)- }- }- w++- }- val j: mut usize = 0- for j < @len(thread_refs) {- val tr = @get(thread_refs, j)- if tr is some t {- val joined = thread.Thread.join[allocators.HeapAllocator](ac, t)- match joined {- ok _ => {- }- err _ => {- }- }- }- j++- }- for job in jobs {- val _ = job- }- @listfree(jobs)- @listfree(thread_refs)-}--fn copy_id(id: objid.Id) objid.Id = trust {- val out: ref u8 = @alloc(32) as ref u8- @memcpy(out as ref void, id.ptr as ref void, 32)- return objid.id(out)-}--fn free_meta_list(metas: list[ref records.RecordMeta]) void = trust {- for m in metas {- if m.id.ptr != none {- val ip: mut ref void = m.id.ptr as ref void- @free(ip)- }- val mp: mut ref void = m as ref void- @free(mp)- }- @listfree(metas)-}--pub fn open(repo: layout.Repo) option[ref Writer] = trust {- val tmpdir: str.StringView = layout.tmp_dir(repo)- val packs: str.StringView = layout.packs_dir(repo)- val name_c: ref u8 = @fmtalloc("import-{d}.vpack", {time.now_ns()})- val name: str.StringView = str.from_cstr(name_c)- val tmp: str.StringView = files.join(tmpdir, name)- @free(name_c as ref void)- val fd: i32 = native.open_rw(tmp)- if fd < 0 {- files.free_path(tmpdir)- files.free_path(packs)- files.free_path(tmp)- return none- }- val header: mut buf.Buf = buf.new(16)- buf.Buf.put_raw(header, c"VPK1", 4)- buf.Buf.put_u32_le(header, 1)- buf.Buf.put_u64_le(header, 0)- val wrote: bool = native.write_fd_all(fd, buf.Buf.view(header))- if !wrote {- buf.Buf.free(header)- native.close_fd(fd)- val _ = native.delete_file(tmp)- files.free_path(tmpdir)- files.free_path(packs)- files.free_path(tmp)- return none- }- val w: mut ref Writer = @alloc(@sizeof(Writer)) as ref Writer- w.tmp_path = tmp- w.tmp_dir = tmpdir- w.packs_dir = packs- w.fd = fd- w.count = 0- w.offset = 16- w.metas = lists.new[ref records.RecordMeta]()- w.items = lists.new[ref PendingRecord]()- w.pending_bytes = 0- buf.Buf.free(header)- w.failed = false- w.seen = idmap.new(1024)- return some w-}--/// Append one object with a precomputed ID. Takes ownership of `body`.-pub fn add_known(w: mut Writer, kind: u8, id: objid.Id, body: bytes.Bytes) objid.Id = trust {- if w.failed {- if body.ptr != none {- val bp: mut ref void = body.ptr as ref void- @free(bp)- }- return id- }- val id_view: bytes.Bytes = bytes.bytes(id.ptr, 32)- if idmap.contains(w.seen, id_view) {- if body.ptr != none {- val bp2: mut ref void = body.ptr as ref void- @free(bp2)- }- return id- }- val _ = idmap.put(w.seen, id_view)- val r: mut ref PendingRecord = @alloc(@sizeof(PendingRecord)) as ref PendingRecord- r.id = copy_id(id)- r.kind = kind- r.body = body- r.stored = bytes.empty()- r.comp = 0- @append(w.items, r)- w.pending_bytes = w.pending_bytes + body.len- if w.pending_bytes >= 268435456 {- if !write_pending(w) {- w.failed = true- }- }- return id-}--/// Append one object. Takes ownership of `body`.-pub fn add(w: mut Writer, kind: u8, body: bytes.Bytes) objid.Id = trust {- val id: objid.Id = objid.object_id(kind, body)- return add_known(w, kind, id, body)-}--fn free_writer(w: mut ref Writer) void = trust {- if w.fd >= 0 {- native.close_fd(w.fd)- w.fd = -1- }- free_meta_list(w.metas)- if @len(w.items) > 0 {- free_items(w.items)- } else {- @listfree(w.items)- }- idmap.free(w.seen)- if w.tmp_path.ptr != none {- files.free_path(w.tmp_path)- }- if w.tmp_dir.ptr != none {- files.free_path(w.tmp_dir)- }- if w.packs_dir.ptr != none {- files.free_path(w.packs_dir)- }- @free(w as ref void)-}--pub fn abort(w: mut ref Writer) void = trust {- if !w.failed {- w.failed = true- }- if w.fd >= 0 {- native.close_fd(w.fd)- w.fd = -1- }- val _ = native.delete_file(w.tmp_path)- free_writer(w)-}--fn write_pending(w: mut ref Writer) bool = trust {- if @len(w.items) == 0 {- return true- }- compress_items(w.items)- val i: mut usize = 0- val out: mut buf.Buf = buf.new(8388608)- val header: mut buf.Buf = buf.new(64)- for i < @len(w.items) {- val item = @get(w.items, i)- if item is some r {- buf.Buf.reset(header)- buf.Buf.put_id(header, r.id.ptr)- buf.Buf.put_u8(header, r.kind)- buf.Buf.put_u8(header, r.comp)- buf.Buf.put_varint(header, r.body.len as u64)- buf.Buf.put_varint(header, r.stored.len as u64)- val start: u64 = w.offset- buf.Buf.put_bytes(out, buf.Buf.view(header))- buf.Buf.put_bytes(out, r.stored)- @append(w.metas, records.record_meta(copy_id(r.id), start, r.kind, r.body.len as u64))- w.count++- w.offset = start + header.len as u64 + r.stored.len as u64- if out.len >= 8388608 {- if !native.write_fd_all(w.fd, buf.Buf.view(out)) {- w.failed = true- }- buf.Buf.reset(out)- }- }- i++- }- if out.len > 0 {- if !native.write_fd_all(w.fd, buf.Buf.view(out)) {- w.failed = true- }- buf.Buf.reset(out)- }- buf.Buf.free(out)- buf.Buf.free(header)- if w.failed {- return false- }- free_items(w.items)- w.items = lists.new[ref PendingRecord]()- w.pending_bytes = 0- return true-}--/// Finish the pack and write its index. `w` is consumed.-pub fn finish(w: mut ref Writer) bool = trust {- if w.failed {- abort(w)- return false- }- if !write_pending(w) {- abort(w)- return false- }-- val count_buf: mut buf.Buf = buf.new(8)- buf.Buf.put_u64_le(count_buf, w.count as u64)- val patched: bool = native.pwrite_fd_all(w.fd, 8, buf.Buf.view(count_buf))- buf.Buf.free(count_buf)- if !patched {- abort(w)- return false- }-- if !native.seek_set(w.fd, 0) {- abort(w)- return false- }- val state: ref void = @alloc(b3.hasher_state_size())- b3.hasher_init(state)- val chunk: ref u8 = @alloc(1048576) as ref u8- val hashed: mut bool = true- for {- val n: i64 = native.read_fd(w.fd, chunk, 1048576)- if n < 0 {- hashed = false- break- }- if n == 0 {- break- }- b3.hasher_update(state, chunk, n as usize)- }- val digest: ref u8 = @alloc(32) as ref u8- b3.hasher_final(state, digest)- @free(state)- @free(chunk as ref void)- if !hashed {- @free(digest as ref void)- abort(w)- return false- }- val trailer: bytes.Bytes = bytes.bytes(digest, 32)- val wrote_trailer: bool = native.pwrite_fd_all(w.fd, w.offset as i64, trailer)- val synced: bool = native.fsync_fd(w.fd)- native.close_fd(w.fd)- w.fd = -1- if !wrote_trailer || !synced {- @free(digest as ref void)- val _ = native.delete_file(w.tmp_path)- free_writer(w)- return false- }-- val hex: ref u8 = @alloc(65) as ref u8- objid.hex_encode(digest, 32, hex)- @store8(@ptradd(hex, 64), 0)- val pack_name: str.StringView = str.from_cstr(hex)- val pack_file: str.StringView = files.with_suffix(pack_name, str.from_cstr(c".vpack"))- val idx_file: str.StringView = files.with_suffix(pack_name, str.from_cstr(c".vidx"))- val pack_final: str.StringView = files.join(w.packs_dir, pack_file)- val idx_final: str.StringView = files.join(w.packs_dir, idx_file)- val renamed: bool = native.rename_file(w.tmp_path, pack_final)- if !renamed {- @free(hex as ref void)- @free(digest as ref void)- files.free_path(pack_file)- files.free_path(idx_file)- files.free_path(pack_final)- files.free_path(idx_final)- val _ = native.delete_file(w.tmp_path)- free_writer(w)- return false- }- val _ = native.sync_dir_path(w.packs_dir)-- records.sort_by_id(w.metas)- val index_bytes: bytes.Bytes = index.encode(w.metas, trailer)- val idx_tmp_name: str.StringView = files.with_suffix(pack_name, str.from_cstr(c".vidx.tmp"))- val idx_tmp: str.StringView = files.join(w.tmp_dir, idx_tmp_name)- val wrote_index: bool = native.write_atomic(- idx_tmp,- idx_final,- w.tmp_dir,- w.packs_dir,- index_bytes- )- val idx_buf: mut ref void = index_bytes.ptr as ref void- @free(idx_buf)- files.free_path(idx_tmp_name)- files.free_path(idx_tmp)- files.free_path(pack_file)- files.free_path(idx_file)- files.free_path(pack_final)- files.free_path(idx_final)- @free(hex as ref void)- @free(digest as ref void)- free_writer(w)- return wrote_index-}--- a/src/src/store/zstd.sx+++ /dev/null@@ -1,72 +0,0 @@-/// 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 = 1--/// 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/src/worktree/checkout.sx+++ /dev/null@@ -1,919 +0,0 @@-/// Parallel, path-safe checkout from a veins tree into the working directory.--val str = use("std/string")-val stdio = use("std/stdio")-val msg = use("../core/msg.sx")-val allocators = use("std/allocators")-val thread = use("std/thread")-val bytes = use("../core/bytes.sx")-val lists = use("../core/lists.sx")-val objid = use("../object/id.sx")-val types = use("../object/types.sx")-val names = use("../object/names.sx")-val blob = use("../object/blob.sx")-val tree = use("../object/tree.sx")-val commit = use("../object/commit.sx")-val view = use("../object/view.sx")-val store = use("../store/store.sx")-val layout = use("../store/layout.sx")-val state = use("../store/state.sx")-val files = use("../io/files.sx")-val native = use("../io/native.sx")-val object = use("../git/object.sx")-val lazy = use("../git/lazy.sx")--extern (C) fn openat(dirfd: i32, path: ref u8, flags: i32, mode: i32) i32 = "openat"-extern (C) fn mkdirat(dirfd: i32, path: ref u8, mode: i32) i32 = "mkdirat"-extern (C) fn symlinkat(target: ref u8, newdirfd: i32, linkpath: ref u8) i32 = "symlinkat"-extern (C) fn unlinkat(dirfd: i32, path: ref u8, flags: i32) i32 = "unlinkat"-extern (C) fn close(fd: i32) i32 = "close"-extern (C) fn fchmod(fd: i32, mode: u32) i32 = "fchmod"-extern (C) fn sysconf(name: i32) i64 = "sysconf"--fn o_wronly() i32 = trust {- return 1-}--fn o_creat() i32 = trust {- when linux {- return 64- }- when macos {- return 512- }- return 64-}--fn o_trunc() i32 = trust {- when linux {- return 512- }- when macos {- return 1024- }- return 512-}--fn o_nofollow() i32 = trust {- when linux {- return 131072- }- when macos {- return 256- }- return 0-}--fn o_directory() i32 = trust {- when linux {- return 65536- }- when macos {- return 1048576- }- return 0-}--fn o_cloexec() i32 = trust {- when linux {- return 524288- }- when macos {- return 16777216- }- return 0-}--val DIR_MODE: u32 = 493-val FILE_MODE: u32 = 420-val EXEC_MODE: u32 = 493--fn cpu_count() usize = trust {- when linux {- val n: i64 = sysconf(84)- if n > 0 {- return n as usize- }- }- when macos {- val n2: i64 = sysconf(58)- if n2 > 0 {- return n2 as usize- }- }- return 4-}--pub type CheckoutTask = {- path: mut bytes.Bytes- kind: mut u8- target: mut objid.Id-}--pub type CheckoutWalk = {- handles: list[ref store.Handle]- tasks: mut list[ref CheckoutTask]- dirs: mut list[bytes.Bytes]- failed: mut bool- error: mut bytes.Bytes-}--pub type CheckoutJob = {- handles: mut list[ref store.Handle]- root_fd: mut i32- tasks: mut list[ref CheckoutTask]- start: mut usize- step: mut usize- failed: mut bool- error: mut bytes.Bytes- git: mut object.GitRepo- git_lock: mut ref void- has_git: mut bool-}--type CheckoutTarget = {- fd: i32- name: ref u8- owned_fd: bool-}--fn copy_id(id: objid.Id) objid.Id = trust {- val out: ref u8 = @alloc(32) as ref u8- @memcpy(out as ref void, id.ptr as ref void, 32)- return objid.id(out)-}--fn join_bytes(prefix: bytes.Bytes, name: bytes.Bytes) bytes.Bytes = trust {- if prefix.len == 0 {- return bytes.Bytes.dup(name)- }- val out: ref u8 = @alloc(prefix.len + 1 + name.len) as ref u8- @memcpy(out as ref void, prefix.ptr as ref void, prefix.len)- @store8(@ptradd(out, prefix.len as i64), 47)- @memcpy(@ptradd(out, (prefix.len + 1) as i64) as ref void, name.ptr as ref void, name.len)- return bytes.bytes(out, prefix.len + 1 + name.len)-}--fn component_cstr(path: bytes.Bytes, start: usize, end: usize) ref u8 = trust {- val n: usize = end - start- val out: ref u8 = @alloc(n + 1) as ref u8- if n > 0 {- @memcpy(out as ref void, @ptradd(path.ptr, start as i64) as ref void, n)- }- @store8(@ptradd(out, n as i64), 0)- return out-}--fn next_slash(path: bytes.Bytes, start: usize) usize = trust {- val i: mut usize = start- for i < path.len && bytes.Bytes.at(path, i) != 47 {- i++- }- return i-}--fn valid_checkout_name(name: bytes.Bytes) bool = trust {- if !names.valid_name(name) {- return false- }- if bytes.Bytes.eql_ascii_ci(name, bytes.bytes(c".git", 4)) {- return false- }- return true-}--fn ensure_dir(root_fd: i32, path: bytes.Bytes) bool = trust {- val pos: mut usize = 0- val cur: mut i32 = root_fd- val owned: mut bool = false- for pos < path.len {- val end: usize = next_slash(path, pos)- if end == pos {- if owned {- close(cur)- }- return false- }- val comp: ref u8 = component_cstr(path, pos, end)- val flags: i32 = o_directory() | o_nofollow() | o_cloexec()- val next: mut i32 = openat(cur, comp, flags, 0)- if next < 0 {- val made: i32 = mkdirat(cur, comp, DIR_MODE as i32)- if made != 0 {- next = openat(cur, comp, flags, 0)- } else {- next = openat(cur, comp, flags, 0)- }- }- @free(comp as ref void)- if next < 0 {- if owned {- close(cur)- }- return false- }- if owned {- close(cur)- }- cur = next- owned = true- if end == path.len {- break- }- pos = end + 1- }- if owned {- close(cur)- }- return true-}--fn open_parent(root_fd: i32, path: bytes.Bytes) option[CheckoutTarget] = trust {- val last_slash: mut i64 = -1- val i: mut usize = 0- for i < path.len {- if bytes.Bytes.at(path, i) == 47 {- last_slash = i as i64- }- i++- }- val cur: mut i32 = root_fd- val owned: mut bool = false- if last_slash >= 0 {- val pos: mut usize = 0- val stop: usize = last_slash as usize- for pos < stop {- val end: usize = next_slash(path, pos)- if end == pos || end > stop {- if owned {- close(cur)- }- return none- }- val comp: ref u8 = component_cstr(path, pos, end)- val next: i32 = openat(cur, comp, o_directory() | o_nofollow() | o_cloexec(), 0)- @free(comp as ref void)- if next < 0 {- if owned {- close(cur)- }- return none- }- if owned {- close(cur)- }- cur = next- owned = true- pos = end + 1- }- }- val name_start: mut usize = 0- if last_slash >= 0 {- name_start = last_slash as usize + 1- }- if name_start >= path.len {- if owned {- close(cur)- }- return none- }- val name: ref u8 = component_cstr(path, name_start, path.len)- return some CheckoutTarget{fd: cur, name: name, owned_fd: owned}-}--fn close_target(t: CheckoutTarget) void = trust {- if t.owned_fd {- close(t.fd)- }- val np: mut ref void = t.name as ref void- @free(np)-}--fn read_git_blob(- git: object.GitRepo,- lock: ref void,- has_git: bool,- blob_id: objid.Id-) option[bytes.Bytes] = trust {- if !has_git || lock == none {- return none- }- thread.Mutex.lock(lock)- val read = object.read_fast(git, lazy.git_oid(blob_id))- val out: mut option[bytes.Bytes] = none- match read {- ok o => {- if o.kind == object.KIND_BLOB {- out = some bytes.Bytes.dup(o.body)- }- object.free_object(o)- }- err _ => {- }- }- thread.Mutex.unlock(lock)- return out-}--fn write_blob_data(- handles: list[ref store.Handle],- fd: i32,- blob_id: objid.Id,- depth: usize,- git: object.GitRepo,- git_lock: ref void,- has_git: bool-) bool = trust {- if depth > 64 {- return false- }- if lazy.is_lazy(blob_id) {- val git_body = read_git_blob(git, git_lock, has_git, blob_id)- match git_body {- some b => {- val wrote: bool = native.write_fd_all(fd, b)- files.free_buffer(b)- return wrote- }- none => {- return false- }- }- }- val body_opt = state.read_body(handles, blob_id, types.BLOB)- val body: mut bytes.Bytes = bytes.empty()- match body_opt {- some b => {- body = b- }- none => {- return false- }- }- val decoded = blob.decode(body)- val b: mut ref blob.Blob = none- match decoded {- ok x => {- b = x- }- err _ => {- files.free_buffer(body)- return false- }- }- val success: mut bool = true- if b.form == blob.FORM_INLINE {- success = native.write_fd_all(fd, b.data)- } elif b.form == blob.FORM_LEAF {- for e in b.entries {- val chunk_opt = state.read_body(handles, e.id, types.CHUNK)- match chunk_opt {- some chunk => {- if !native.write_fd_all(fd, chunk) {- success = false- }- files.free_buffer(chunk)- }- none => {- success = false- }- }- if !success {- break- }- }- } else {- for e in b.entries {- if !write_blob_data(handles, fd, e.id, depth + 1, git, git_lock, has_git) {- success = false- break- }- }- }- blob.free_blob(b)- files.free_buffer(body)- return success-}--fn write_symlink(- handles: list[ref store.Handle],- t: CheckoutTarget,- blob_id: objid.Id,- git: object.GitRepo,- git_lock: ref void,- has_git: bool-) bool = trust {- if lazy.is_lazy(blob_id) {- val git_body = read_git_blob(git, git_lock, has_git, blob_id)- match git_body {- some b => {- val target: ref u8 = @alloc(b.len + 1) as ref u8- if b.len > 0 {- @memcpy(target as ref void, b.ptr as ref void, b.len)- }- @store8(@ptradd(target, b.len as i64), 0)- val _ = unlinkat(t.fd, t.name, 0)- val created: bool = symlinkat(target, t.fd, t.name) == 0- @free(target as ref void)- files.free_buffer(b)- return created- }- none => {- return false- }- }- }- val body_opt = state.read_body(handles, blob_id, types.BLOB)- val body: mut bytes.Bytes = bytes.empty()- match body_opt {- some b => {- body = b- }- none => {- return false- }- }- val decoded = blob.decode(body)- val b: mut ref blob.Blob = none- match decoded {- ok x => {- b = x- }- err _ => {- files.free_buffer(body)- return false- }- }- val success: mut bool = false- if b.form == blob.FORM_INLINE {- val target: ref u8 = @alloc(b.data.len + 1) as ref u8- if b.data.len > 0 {- @memcpy(target as ref void, b.data.ptr as ref void, b.data.len)- }- @store8(@ptradd(target, b.data.len as i64), 0)- val _ = unlinkat(t.fd, t.name, 0)- success = symlinkat(target, t.fd, t.name) == 0- @free(target as ref void)- }- blob.free_blob(b)- files.free_buffer(body)- return success-}--fn write_task(job: ref CheckoutJob, task: ref CheckoutTask) bool = trust {- val target_opt = open_parent(job.root_fd, task.path)- match target_opt {- some t => {- val success: mut bool = false- if task.kind == tree.KIND_SYMLINK {- success = write_symlink(- job.handles,- t,- task.target,- job.git,- job.git_lock,- job.has_git- )- } else {- val flags: i32 = o_wronly() | o_creat() | o_trunc() | o_nofollow() | o_cloexec()- val mode: u32 = FILE_MODE- val mut_fd: mut i32 = openat(t.fd, t.name, flags, mode as i32)- if mut_fd < 0 {- val _ = unlinkat(t.fd, t.name, 0)- mut_fd = openat(t.fd, t.name, flags, mode as i32)- }- val fd: i32 = mut_fd- if fd >= 0 {- success = write_blob_data(- job.handles,- fd,- task.target,- 0,- job.git,- job.git_lock,- job.has_git- )- if success {- val want: mut u32 = FILE_MODE- if task.kind == tree.KIND_EXECUTABLE {- want = EXEC_MODE- }- if fchmod(fd, want) != 0 {- success = false- }- }- close(fd)- }- }- close_target(t)- return success- }- none => {- return false- }- }-}--fn checkout_worker(arg: ref void) ref void = trust {- val job: mut ref CheckoutJob = arg as ref CheckoutJob- val i: mut usize = job.start- for i < @len(job.tasks) {- val item = @get(job.tasks, i)- if item is some task {- if !write_task(job, task) {- job.failed = true- job.error = bytes.Bytes.dup(task.path)- break- }- }- i = i + job.step- }- return none-}--fn add_task(- walk: mut CheckoutWalk,- path: bytes.Bytes,- kind: u8,- target: objid.Id-) void = trust {- val t: mut ref CheckoutTask = @alloc(@sizeof(CheckoutTask)) as ref CheckoutTask- t.path = path- t.kind = kind- t.target = copy_id(target)- @append(walk.tasks, t)-}--fn walk_tree(- walk: mut CheckoutWalk,- tree_id: objid.Id,- prefix: bytes.Bytes,- depth: usize-) void = trust {- if walk.failed {- return- }- if depth > 4096 {- walk.failed = true- return- }- val body_opt = state.read_body(walk.handles, tree_id, types.TREE)- val body: mut bytes.Bytes = bytes.empty()- match body_opt {- some b => {- body = b- }- none => {- walk.failed = true- return- }- }- val decoded = tree.decode(body)- val t: mut ref tree.Tree = none- match decoded {- ok x => {- t = x- }- err _ => {- files.free_buffer(body)- walk.failed = true- return- }- }- for e in t.entries {- if walk.failed {- break- }- if !valid_checkout_name(e.name) {- walk.failed = true- break- }- val path: bytes.Bytes = join_bytes(prefix, e.name)- if e.kind == tree.KIND_SUBTREE {- @append(walk.dirs, path)- walk_tree(walk, e.target, path, depth + 1)- } elif e.kind == tree.KIND_FILE- || e.kind == tree.KIND_EXECUTABLE- || e.kind == tree.KIND_SYMLINK {- add_task(walk, path, e.kind, e.target)- } elif e.kind == tree.KIND_SUBMODULE {- @append(walk.dirs, path)- } else {- files.free_buffer(path)- walk.failed = true- }- }- tree.free_tree(t)- files.free_buffer(body)-}--fn parse_veins_hex(hex: bytes.Bytes) option[objid.Id] = trust {- if hex.len != 64 {- return none- }- val raw: ref u8 = @alloc(32) as ref u8- val i: mut usize = 0- for i < 32 {- val hi_c: u8 = bytes.Bytes.at(hex, i * 2)- val lo_c: u8 = bytes.Bytes.at(hex, i * 2 + 1)- val hi: mut i32 = -1- val lo: mut i32 = -1- if hi_c >= 48 && hi_c <= 57 {- hi = (hi_c - 48) as i32- } elif hi_c >= 97 && hi_c <= 102 {- hi = (hi_c - 87) as i32- } elif hi_c >= 65 && hi_c <= 70 {- hi = (hi_c - 55) as i32- }- if lo_c >= 48 && lo_c <= 57 {- lo = (lo_c - 48) as i32- } elif lo_c >= 97 && lo_c <= 102 {- lo = (lo_c - 87) as i32- } elif lo_c >= 65 && lo_c <= 70 {- lo = (lo_c - 55) as i32- }- if hi < 0 || lo < 0 {- @free(raw as ref void)- return none- }- @store8(@ptradd(raw, i as i64), ((hi * 16 + lo) as u8))- i++- }- return some objid.id(raw)-}--fn bookmark_target(v: ref view.View, name: bytes.Bytes) option[objid.Id] = trust {- for bm in v.bookmarks {- if bytes.Bytes.eql(bm.name, name) {- if @len(bm.targets.adds) == 1 {- val a = @get(bm.targets.adds, 0)- if a is some id {- return some id- }- }- return none- }- }- return none-}--fn tag_target(v: ref view.View, name: bytes.Bytes) option[objid.Id] = trust {- for t in v.tags {- if bytes.Bytes.eql(t.name, name) {- return some t.target- }- }- return none-}--fn working_copy_target(v: ref view.View) option[objid.Id] = trust {- for w in v.working_copies {- if bytes.Bytes.eql(w.workspace, bytes.bytes(c"default", 7)) {- return some w.target- }- }- return none-}--fn resolve_revision(v: ref view.View, rev: bytes.Bytes) option[objid.Id] = trust {- if rev.len == 0 || bytes.Bytes.eql(rev, bytes.bytes(c"@", 1)) {- return working_copy_target(v)- }- val bm = bookmark_target(v, rev)- if bm is some id {- return some id- }- val tg = tag_target(v, rev)- if tg is some id2 {- return some id2- }- return parse_veins_hex(rev)-}--/// Check out `rev` (empty means the working-copy commit) into the repository.-pub fn run(repo: layout.Repo, rev: bytes.Bytes) i32 = trust {- val store_handle: mut store.Store = store.open_all(repo)- val mut_view = state.current_view(repo, store_handle.handles)- val v: mut ref view.View = none- match mut_view {- some x => {- v = x- }- none => {- msg.error_prefix()- stdio.eprint("no operation state; import a repository first\n", {})- store.close(store_handle)- return 1- }- }- val target_opt = resolve_revision(v, rev)- val commit_id: mut objid.Id = objid.id_none()- match target_opt {- some id => {- commit_id = id- }- none => {- msg.error_prefix()- stdio.eprint("unknown revision: {s}\n", {str.view(rev.ptr, rev.len as i64)})- view.free_view(v)- store.close(store_handle)- return 1- }- }- val cbody_opt = state.read_body(store_handle.handles, commit_id, types.COMMIT)- val cbody: mut bytes.Bytes = bytes.empty()- match cbody_opt {- some b => {- cbody = b- }- none => {- msg.error_prefix()- stdio.eprint("cannot read commit\n", {})- view.free_view(v)- store.close(store_handle)- return 1- }- }- val cdecoded = commit.decode(cbody)- val c: mut ref commit.Commit = none- match cdecoded {- ok x => {- c = x- }- err _ => {- files.free_buffer(cbody)- msg.error_prefix()- stdio.eprint("corrupt commit\n", {})- view.free_view(v)- store.close(store_handle)- return 1- }- }- val root_tree: objid.Id = copy_id(c.root_tree)- commit.free_commit(c)- files.free_buffer(cbody)- view.free_view(v)-- val root: str.StringView = layout.root_view(repo)- val root_c: ref u8 = bytes.Bytes.to_cstr(bytes.from_cstr(root.ptr))- val root_fd: i32 = openat(-100, root_c, o_directory() | o_cloexec(), 0)- @free(root_c as ref void)- if root_fd < 0 {- msg.error_prefix()- stdio.eprint("cannot open working directory\n", {})- store.close(store_handle)- return 1- }-- val tasks: list[ref CheckoutTask] = lists.new[ref CheckoutTask]()- val dirs: list[bytes.Bytes] = lists.new[bytes.Bytes]()- val walk: mut CheckoutWalk = CheckoutWalk{- handles: store_handle.handles,- tasks: tasks,- dirs: dirs,- failed: false,- error: bytes.empty()- }- walk_tree(walk, root_tree, bytes.empty(), 0)- if walk.failed {- msg.error_prefix()- stdio.eprint("checkout tree validation failed\n", {})- close(root_fd)- store.close(store_handle)- return 1- }-- val dir_failed: mut bool = false- for d in dirs {- if !ensure_dir(root_fd, d) {- dir_failed = true- msg.error_prefix()- stdio.eprint("cannot create directory: {s}\n", {str.view(d.ptr, d.len as i64)})- break- }- }- if dir_failed {- close(root_fd)- store.close(store_handle)- return 1- }-- val ac: allocators.HeapAllocator = @zeroed- val git_path: str.StringView = layout.git_dir(repo)- val git_opt = object.open(git_path)- val git_repo: mut object.GitRepo = @zeroed- val git_open: mut bool = false- match git_opt {- ok g => {- git_repo = g- git_open = true- }- err _ => {- files.free_path(git_path)- }- }- val git_lock_opt = thread.Mutex.new[allocators.HeapAllocator](ac)- val git_lock: mut ref void = none- val git_usable: mut bool = git_open- match git_lock_opt {- some m => {- git_lock = m- }- none => {- git_usable = false- }- }- val count: usize = cpu_count()- val n: usize = @len(tasks)- val workers: mut usize = count- if workers < 1 {- workers = 1- }- if workers > n && n > 0 {- workers = n- }- val thread_refs: mut list[ref void] = lists.new[ref void]()- val jobs: mut list[ref CheckoutJob] = lists.new[ref CheckoutJob]()- if n == 0 {- workers = 0- }- val w: mut usize = 0- for w < workers {- val job: mut ref CheckoutJob = @alloc(@sizeof(CheckoutJob)) as ref CheckoutJob- job.handles = store_handle.handles- job.root_fd = root_fd- job.tasks = tasks- job.start = w- job.step = workers- job.failed = false- job.error = bytes.empty()- job.git = git_repo- job.git_lock = git_lock- job.has_git = git_usable- @append(jobs, job)- val tr = thread.Thread.new[allocators.HeapAllocator](ac, checkout_worker, job as ref void)- match tr {- ok t => {- @append(thread_refs, t)- }- err _ => {- job.failed = true- job.error = bytes.Bytes.dup(bytes.from_cstr(c"cannot start checkout thread"))- }- }- w++- }-- val failed_path: mut bytes.Bytes = bytes.empty()- val had_failure: mut bool = false- val j: mut usize = 0- for j < @len(jobs) {- val job = @get(jobs, j)- if job is some jb {- val tr = @get(thread_refs, j)- if tr is some t {- val joined = thread.Thread.join[allocators.HeapAllocator](ac, t)- match joined {- ok _ => {- }- err _ => {- }- }- }- if jb.failed {- had_failure = true- if failed_path.len == 0 && jb.error.len > 0 {- failed_path = jb.error- }- }- }- j++- }-- if git_lock != none {- thread.Mutex.free[allocators.HeapAllocator](ac, git_lock)- }- if git_open {- object.free(git_repo)- }- close(root_fd)- if had_failure {- if failed_path.len > 0 {- msg.error_prefix()- stdio.eprint(- "checkout failed at: {s}\n",- {str.view(failed_path.ptr, failed_path.len as i64)}- )- } else {- msg.error_prefix()- stdio.eprint("checkout failed\n", {})- }- store.close(store_handle)- return 1- }-- msg.info_prefix()- stdio.print("checked out {d} files\n", {n})- store.close(store_handle)- return 0-}--- a/src/src/worktree/ignore.sx+++ /dev/null@@ -1,307 +0,0 @@-/// Gitignore-style ignore rules for working-copy snapshots.-///-/// Supports the subset of `.vnexclude` / `.gitignore` syntax that matters for-/// deciding which new files enter a snapshot: comments, negation, directory-/// patterns, anchored patterns, `*`, `?`, and `**`.--val str = use("std/string")-val bytes = use("../core/bytes.sx")-val lists = use("../core/lists.sx")-val files = use("../io/files.sx")--pub type Rule = {- pattern: mut bytes.Bytes- negated: mut bool- dir_only: mut bool- anchored: mut bool- has_slash: mut bool- base: mut bytes.Bytes-}--pub type Rules = {- items: mut list[ref Rule]-}--fn new_rule(- pattern: bytes.Bytes,- negated: bool,- dir_only: bool,- anchored: bool,- has_slash: bool,- base: bytes.Bytes-) ref Rule = trust {- val r: mut ref Rule = @alloc(@sizeof(Rule)) as ref Rule- r.pattern = bytes.Bytes.dup(pattern)- r.negated = negated- r.dir_only = dir_only- r.anchored = anchored- r.has_slash = has_slash- r.base = bytes.Bytes.dup(base)- return r-}--pub fn empty() Rules = trust {- return Rules{items: lists.new[ref Rule]()}-}--fn trim(b: bytes.Bytes) bytes.Bytes = trust {- val start: mut usize = 0- val end: mut usize = b.len- for start < end {- val c: u8 = bytes.Bytes.at(b, start)- if c != 32 && c != 9 && c != 13 {- break- }- start++- }- for end > start {- val c2: u8 = bytes.Bytes.at(b, end - 1)- if c2 != 32 && c2 != 9 && c2 != 13 {- break- }- end--- }- return bytes.Bytes.slice(b, start, end)-}--fn add_line(rules: mut Rules, base: bytes.Bytes, line_in: bytes.Bytes) void = trust {- val line: bytes.Bytes = trim(line_in)- if line.len == 0 {- return- }- if bytes.Bytes.at(line, 0) == 35 {- return- }- val negated: mut bool = false- val start: mut usize = 0- if bytes.Bytes.at(line, 0) == 33 {- negated = true- start = 1- }- if start >= line.len {- return- }- val mut_end: mut usize = line.len- val dir_only: mut bool = false- if bytes.Bytes.at(line, mut_end - 1) == 47 {- dir_only = true- mut_end--- }- if start >= mut_end {- return- }- val anchored: mut bool = false- if bytes.Bytes.at(line, start) == 47 {- anchored = true- start++- }- if start >= mut_end {- return- }- val pattern: bytes.Bytes = bytes.Bytes.slice(line, start, mut_end)- val has_slash: mut bool = false- val i: mut usize = 0- for i < pattern.len {- if bytes.Bytes.at(pattern, i) == 47 {- has_slash = true- }- i++- }- @append(- rules.items,- new_rule(pattern, negated, dir_only, anchored, has_slash, base)- )-}--pub fn load_file(- rules: mut Rules,- repo_root: str.StringView,- base: bytes.Bytes,- name: str.StringView-) void = trust {- val base_view: str.StringView = files.to_view(base)- val dir: str.StringView = files.join(repo_root, base_view)- val path: str.StringView = files.join(dir, name)- val data_opt = files.read_all(path)- files.free_path(dir)- files.free_path(path)- if data_opt is some data {- val pos: mut usize = 0- val line_start: mut usize = 0- for pos <= data.len {- val at_end: bool = pos == data.len- if at_end || bytes.Bytes.at(data, pos) == 10 {- add_line(rules, base, bytes.Bytes.slice(data, line_start, pos))- line_start = pos + 1- }- pos++- }- files.free_buffer(data)- }-}--/// Load root-level `.vnexclude` and `.gitignore`. Per-directory files are-/// added during traversal by `load_file`.-pub fn load_root(rules: mut Rules, repo_root: str.StringView) void = trust {- load_file(rules, repo_root, bytes.empty(), str.from_cstr(c".vnexclude"))- load_file(rules, repo_root, bytes.empty(), str.from_cstr(c".gitignore"))-}--fn glob_here(pattern: bytes.Bytes, pi: usize, text: bytes.Bytes, ti: usize) bool = trust {- if pi >= pattern.len {- return ti >= text.len- }- val pc: u8 = bytes.Bytes.at(pattern, pi)- if pc == 42 {- val double: bool = pi + 1 < pattern.len && bytes.Bytes.at(pattern, pi + 1) == 42- if double {- val next: usize = pi + 2- if next < pattern.len && bytes.Bytes.at(pattern, next) == 47 {- val after: usize = next + 1- val j: mut usize = ti- for {- if glob_here(pattern, after, text, j) {- return true- }- if j >= text.len {- break- }- if bytes.Bytes.at(text, j) == 47 {- j++- continue- }- j++- for j < text.len && bytes.Bytes.at(text, j) != 47 {- j++- }- }- return false- }- val j2: mut usize = ti- for {- if glob_here(pattern, next, text, j2) {- return true- }- if j2 >= text.len {- break- }- j2++- }- return false- }- val j3: mut usize = ti- for {- if glob_here(pattern, pi + 1, text, j3) {- return true- }- if j3 >= text.len || bytes.Bytes.at(text, j3) == 47 {- break- }- j3++- }- return false- }- if ti >= text.len {- return false- }- if pc == 63 {- if bytes.Bytes.at(text, ti) == 47 {- return false- }- return glob_here(pattern, pi + 1, text, ti + 1)- }- if pc != bytes.Bytes.at(text, ti) {- return false- }- return glob_here(pattern, pi + 1, text, ti + 1)-}--fn component_end(text: bytes.Bytes, start: usize) usize = trust {- val i: mut usize = start- for i < text.len && bytes.Bytes.at(text, i) != 47 {- i++- }- return i-}--fn match_component(pattern: bytes.Bytes, text: bytes.Bytes) bool = trust {- return glob_here(pattern, 0, text, 0)-}--fn relative_to(base: bytes.Bytes, path: bytes.Bytes) option[bytes.Bytes] = trust {- if base.len == 0 {- return some path- }- if path.len <= base.len {- return none- }- val prefix: bytes.Bytes = bytes.Bytes.slice(path, 0, base.len)- if !bytes.Bytes.eql(prefix, base) {- return none- }- if bytes.Bytes.at(path, base.len) != 47 {- return none- }- return some bytes.Bytes.slice(path, base.len + 1, path.len)-}--fn rule_matches(rule: ref Rule, path: bytes.Bytes, is_dir: bool) bool = trust {- val rel_opt = relative_to(rule.base, path)- val rel: mut bytes.Bytes = bytes.empty()- match rel_opt {- some r => {- rel = r- }- none => {- return false- }- }- if rel.len == 0 {- return false- }- if rule.dir_only && !is_dir {- return false- }- if !rule.has_slash && !rule.anchored {- val start: mut usize = 0- for {- val end: usize = component_end(rel, start)- if match_component(rule.pattern, bytes.Bytes.slice(rel, start, end)) {- return true- }- if end >= rel.len {- break- }- start = end + 1- }- return false- }- return glob_here(rule.pattern, 0, rel, 0)-}--/// True when `path` is ignored. Later rules override earlier ones.-pub fn ignored(rules: Rules, path: bytes.Bytes, is_dir: bool) bool = trust {- val ignored_flag: mut bool = false- for r in rules.items {- if rule_matches(r, path, is_dir) {- ignored_flag = !r.negated- }- }- return ignored_flag-}--pub fn free(rules: Rules) void = trust {- for r in rules.items {- if r.pattern.ptr != none {- val pp: mut ref void = r.pattern.ptr as ref void- @free(pp)- }- if r.base.ptr != none {- val bp: mut ref void = r.base.ptr as ref void- @free(bp)- }- val rp: mut ref void = r as ref void- @free(rp)- }- @listfree(rules.items)-}--- a/src/src/worktree/snapshot.sx+++ /dev/null@@ -1,998 +0,0 @@-/// Working-copy snapshotting.-///-/// Before a command reads or writes the working copy, veins snapshots the files-/// on disk into the working-copy commit. The commit keeps its change ID and-/// message and is amended in place. A snapshot that produces the same tree as-/// the existing commit does not create an operation.--val str = use("std/string")-val stdio = use("std/stdio")-val msg = use("../core/msg.sx")-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 random = use("std/crypto/random")-val objid = use("../object/id.sx")-val types = use("../object/types.sx")-val tree = use("../object/tree.sx")-val commit = use("../object/commit.sx")-val blob = use("../object/blob.sx")-val treewalk = use("../object/treewalk.sx")-val store = use("../store/store.sx")-val layout = use("../store/layout.sx")-val state = use("../store/state.sx")-val txn = use("../store/txn.sx")-val viewops = use("../store/viewops.sx")-val identity = use("../core/identity.sx")-val gitmap = use("../git/map.sx")-val view = use("../object/view.sx")-val files = use("../io/files.sx")-val native = use("../io/native.sx")-val stat = use("../io/stat.sx")-val raw = use("../object/raw.sx")-val ignore = use("ignore.sx")--type CacheEntry = {- path: mut bytes.Bytes- size: mut u64- mtime_ns: mut u64- inode: mut u64- kind: mut u8- executable: mut bool- target: mut objid.Id-}--type Cache = {- entries: mut list[ref CacheEntry]- written_ms: mut i64-}--fn copy_id(id: objid.Id) objid.Id = trust {- val out: ref u8 = @alloc(32) as ref u8- @memcpy(out as ref void, id.ptr as ref void, 32)- return objid.id(out)-}--fn join_path(prefix: bytes.Bytes, name: bytes.Bytes) bytes.Bytes = trust {- if prefix.len == 0 {- return bytes.Bytes.dup(name)- }- val out: ref u8 = @alloc(prefix.len + 1 + name.len) as ref u8- @memcpy(out as ref void, prefix.ptr as ref void, prefix.len)- @store8(@ptradd(out, prefix.len as i64), 47)- @memcpy(- @ptradd(out, (prefix.len + 1) as i64) as ref void,- name.ptr as ref void,- name.len- )- return bytes.bytes(out, prefix.len + 1 + name.len)-}--fn new_entry(- path: bytes.Bytes,- info: stat.StatInfo,- executable: bool,- target: objid.Id-) ref CacheEntry = trust {- val e: mut ref CacheEntry = @alloc(@sizeof(CacheEntry)) as ref CacheEntry- e.path = path- e.size = info.size- e.mtime_ns = info.mtime_ns- e.inode = info.inode- e.kind = info.kind- e.executable = executable- e.target = copy_id(target)- return e-}--fn free_entry(e: ref CacheEntry) void = trust {- if e.path.ptr != none {- val pp: mut ref void = e.path.ptr as ref void- @free(pp)- }- if e.target.ptr != none {- val tp: mut ref void = e.target.ptr as ref void- @free(tp)- }- val ep: mut ref void = e as ref void- @free(ep)-}--fn free_cache(c: Cache) void = trust {- for e in c.entries {- free_entry(e)- }- @listfree(c.entries)-}--fn entry_at(xs: list[ref CacheEntry], i: usize) ref CacheEntry = trust {- val o = @get(xs, i)- if o is some e {- return e- }- assert false- return none-}--fn sort_cache(xs: mut list[ref CacheEntry]) void = trust {- val n: usize = @len(xs)- val i: mut usize = 1- for i < n {- val cur = @get(xs, i)- val c: mut ref CacheEntry = none- if cur is some v {- c = v- }- val j: mut usize = i- for j > 0 {- val prev_opt = @get(xs, j - 1)- val prev: mut ref CacheEntry = none- if prev_opt is some v2 {- prev = v2- }- if bytes.Bytes.cmp(prev.path, c.path) <= 0 {- break- }- @set(xs, j, prev)- j--- }- @set(xs, j, c)- i++- }-}--fn cache_lookup(c: Cache, path: bytes.Bytes) option[ref CacheEntry] = trust {- val lo: mut usize = 0- val hi: mut usize = @len(c.entries)- for lo < hi {- val mid: usize = lo + (hi - lo) / 2- val e: ref CacheEntry = entry_at(c.entries, mid)- val cmp: i64 = bytes.Bytes.cmp(e.path, path)- if cmp == 0 {- return some e- }- if cmp < 0 {- lo = mid + 1- } else {- hi = mid- }- }- return none-}--fn cache_u8(r: mut reader.Reader) option[u8] = trust {- val x = reader.Reader.read_u8(r)- match x {- ok v => {- return some(v)- }- err _ => {- return none- }- }-}--fn cache_u64(r: mut reader.Reader) option[u64] = trust {- val x = reader.Reader.read_u64_le(r)- match x {- ok v => {- return some(v)- }- err _ => {- return none- }- }-}--fn cache_varint(r: mut reader.Reader) option[u64] = trust {- val x = reader.Reader.read_varint(r)- match x {- ok v => {- return some(v)- }- err _ => {- return none- }- }-}--fn cache_bytes(r: mut reader.Reader, max: usize) option[bytes.Bytes] = trust {- val x = reader.Reader.read_bytes(r, max)- match x {- ok v => {- return some(v)- }- err _ => {- return none- }- }-}--fn cache_id(r: mut reader.Reader) option[ref u8] = trust {- val x = reader.Reader.read_id(r)- match x {- ok v => {- return some(v)- }- err _ => {- return none- }- }-}--fn load_cache(repo: layout.Repo) Cache = trust {- val c: mut Cache = Cache{entries: lists.new[ref CacheEntry](), written_ms: 0}- val dir: str.StringView = layout.working_copy_dir(repo)- val path: str.StringView = files.join(dir, str.from_cstr(c"stat-cache"))- files.free_path(dir)- val data_opt = files.read_all(path)- files.free_path(path)- val data: mut bytes.Bytes = bytes.empty()- match data_opt {- some d => {- data = d- }- none => {- return c- }- }- if data.len < 13 || !bytes.Bytes.eql(bytes.Bytes.slice(data, 0, 4), bytes.bytes(c"VST1", 4)) {- files.free_buffer(data)- return c- }- val r: mut reader.Reader = reader.new(data.ptr, data.len)- val version_opt = cache_u8(r)- val version: mut u8 = 0- match version_opt {- some v => {- version = v- }- none => {- files.free_buffer(data)- return c- }- }- if version != 49 {- files.free_buffer(data)- return c- }- val written_opt = cache_u64(r)- match written_opt {- some written => {- c.written_ms = written as i64- }- none => {- files.free_buffer(data)- return c- }- }- val count_opt = cache_varint(r)- val count: mut usize = 0- match count_opt {- some v => {- count = v as usize- }- none => {- files.free_buffer(data)- return c- }- }- val i: mut usize = 0- for i < count {- val p_opt = cache_bytes(r, 65536)- val p: mut bytes.Bytes = bytes.empty()- match p_opt {- some v => {- p = v- }- none => {- break- }- }- val sz_o = cache_u64(r)- val mt_o = cache_u64(r)- val ino_o = cache_u64(r)- val kind_o = cache_u8(r)- val ex_o = cache_u8(r)- val idp_o = cache_id(r)- if sz_o is none {- break- }- if mt_o is none {- break- }- if ino_o is none {- break- }- if kind_o is none {- break- }- if ex_o is none {- break- }- if idp_o is none {- break- }- val sz: mut u64 = 0- val mt: mut u64 = 0- val ino: mut u64 = 0- val kind: mut u8 = 0- val ex: mut u8 = 0- val idp: mut ref u8 = none- if sz_o is some v {- sz = v- }- if mt_o is some v {- mt = v- }- if ino_o is some v {- ino = v- }- if kind_o is some v {- kind = v- }- if ex_o is some v {- ex = v- }- if idp_o is some v {- idp = v- }- val e: mut ref CacheEntry = @alloc(@sizeof(CacheEntry)) as ref CacheEntry- e.path = bytes.Bytes.dup(p)- e.size = sz- e.mtime_ns = mt- e.inode = ino- e.kind = kind- e.executable = ex != 0- e.target = copy_id(objid.id(idp))- @append(c.entries, e)- i++- }- files.free_buffer(data)- sort_cache(c.entries)- return c-}--fn save_cache(repo: layout.Repo, c: Cache) bool = trust {- val b: mut buf.Buf = buf.new(4096)- buf.Buf.put_raw(b, c"VST1", 4)- buf.Buf.put_u8(b, 49)- buf.Buf.put_u64_le(b, time.unix_now_millis() as u64)- buf.Buf.put_varint(b, @len(c.entries) as u64)- for e in c.entries {- buf.Buf.put_length_prefixed(b, e.path)- buf.Buf.put_u64_le(b, e.size)- buf.Buf.put_u64_le(b, e.mtime_ns)- buf.Buf.put_u64_le(b, e.inode)- buf.Buf.put_u8(b, e.kind)- val ex: mut u8 = 0- if e.executable {- ex = 1- }- buf.Buf.put_u8(b, ex)- buf.Buf.put_id(b, e.target.ptr)- }- val dir: str.StringView = layout.working_copy_dir(repo)- val final: str.StringView = files.join(dir, str.from_cstr(c"stat-cache"))- val tmpd: str.StringView = layout.tmp_dir(repo)- val tmp: str.StringView = files.join(tmpd, str.from_cstr(c"stat-cache.tmp"))- val wrote: bool = native.write_atomic(tmp, final, tmpd, dir, buf.Buf.view(b))- files.free_path(dir)- files.free_path(final)- files.free_path(tmpd)- files.free_path(tmp)- buf.Buf.free(b)- return wrote-}--fn add_blob_data(tx: mut ref txn.Txn, data: ref u8, len: usize) objid.Id = trust {- val built: ref blob.BlobBuild = blob.build(data, len)- val id: objid.Id = copy_id(blob.root_id(built))- val ri: mut usize = 0- for ri < @len(built.objects) {- val ro = @get(built.objects, ri)- if ro is some obj {- val orf: mut ref raw.RawObject = obj- val oid: objid.Id = objid.id(orf.id)- val _ = txn.add_known(tx, orf.type_byte, oid, orf.body)- orf.body = bytes.empty()- }- ri++- }- blob.free_build(built)- return id-}--fn cache_matches(- e: ref CacheEntry,- info: stat.StatInfo,- executable: bool,- now_ms: i64,- written_ms: i64-) bool = trust {- if e.size != info.size || e.mtime_ns != info.mtime_ns || e.inode != info.inode {- return false- }- if e.executable != executable || e.kind != info.kind {- return false- }- // Files touched inside the racy window are re-verified by content.- val now_ns: i64 = now_ms * 1000000- val written_ns: i64 = written_ms * 1000000- val window: i64 = 2000000000- if info.mtime_ns as i64 >= written_ns - window {- return false- }- if now_ns - (info.mtime_ns as i64) < window {- return false- }- return true-}--fn sort_names(xs: mut list[ref u8]) void = trust {- val n: usize = @len(xs)- val i: mut usize = 1- for i < n {- val cur = @get(xs, i)- val c: mut ref u8 = none- if cur is some v {- c = v- }- val j: mut usize = i- for j > 0 {- val prev_opt = @get(xs, j - 1)- val prev: mut ref u8 = none- if prev_opt is some v2 {- prev = v2- }- val cmp: i64 = bytes.Bytes.cmp(bytes.from_cstr(prev), bytes.from_cstr(c))- if cmp <= 0 {- break- }- @set(xs, j, prev)- j--- }- @set(xs, j, c)- i++- }-}--fn is_meta_name(name: bytes.Bytes) bool = trust {- if bytes.Bytes.eql(name, bytes.bytes(c".veins", 6)) {- return true- }- if bytes.Bytes.eql(name, bytes.bytes(c".git", 4)) {- return true- }- return false-}--fn free_local(local: ignore.Rules, keep: usize) void = trust {- val i: mut usize = keep- for i < @len(local.items) {- val o = @get(local.items, i)- if o is some r {- if r.pattern.ptr != none {- val pp: mut ref void = r.pattern.ptr as ref void- @free(pp)- }- if r.base.ptr != none {- val bp: mut ref void = r.base.ptr as ref void- @free(bp)- }- val rp: mut ref void = r as ref void- @free(rp)- }- i++- }- @listfree(local.items)-}--fn build_dir(- tx: mut ref txn.Txn,- root: str.StringView,- handles: list[ref store.Handle],- rel: bytes.Bytes,- old_tree: option[objid.Id],- base_rules: ignore.Rules,- cache: Cache,- new_cache: mut list[ref CacheEntry],- now_ms: i64-) option[objid.Id] = trust {- val local: mut ignore.Rules = ignore.empty()- for r in base_rules.items {- @append(local.items, r)- }- val keep: usize = @len(local.items)- ignore.load_file(local, root, rel, str.from_cstr(c".vnexclude"))- ignore.load_file(local, root, rel, str.from_cstr(c".gitignore"))-- val old: mut ref tree.Tree = none- val have_old: mut bool = false- if old_tree is some oid {- val t_opt = treewalk.read_tree(handles, oid)- match t_opt {- some t => {- old = t- have_old = true- }- none => {- free_local(local, keep)- return none- }- }- }-- val rel_view: str.StringView = files.to_view(rel)- val dir: str.StringView = files.join(root, rel_view)- if !files.exists_dir(dir) {- files.free_path(dir)- if have_old {- tree.free_tree(old)- }- free_local(local, keep)- return none- }- val names_list: mut list[ref u8] = files.list_dir(dir)- sort_names(names_list)-- val entries: mut list[ref tree.TreeEntry] = lists.new[ref tree.TreeEntry]()- val failed: mut bool = false- for name_c in names_list {- if failed {- break- }- val name: bytes.Bytes = bytes.from_cstr(name_c)- if is_meta_name(name) {- continue- }- val path: bytes.Bytes = join_path(rel, name)- val fs_path: str.StringView = files.join(dir, str.from_cstr(name_c))- val stat_opt = stat.read(fs_path)- files.free_path(fs_path)- if stat_opt is none {- files.free_buffer(path)- continue- }- val info: mut stat.StatInfo = stat.StatInfo{- kind: 0,- executable: false,- size: 0,- mtime_ns: 0,- inode: 0- }- match stat_opt {- some si => {- info = si- }- none => {- files.free_buffer(path)- continue- }- }- if info.kind == stat.KIND_MISSING {- files.free_buffer(path)- continue- }- val is_dir: bool = info.kind == stat.KIND_DIR- val ignored: bool = ignore.ignored(local, path, is_dir)- val old_idx: mut i32 = -1- if have_old {- old_idx = treewalk.find_name(old, name)- }- if ignored && old_idx < 0 {- files.free_buffer(path)- continue- }- if is_dir {- val child_old: mut option[objid.Id] = none- if have_old && old_idx >= 0 {- val oe = @get(old.entries, old_idx as usize)- if oe is some e {- if e.kind == tree.KIND_SUBTREE {- child_old = some copy_id(e.target)- }- }- }- val child_opt = build_dir(- tx,- root,- handles,- path,- child_old,- local,- cache,- new_cache,- now_ms- )- if child_old is some co {- if co.ptr != none {- val cp: mut ref void = co.ptr as ref void- @free(cp)- }- }- if child_opt is some cid {- @append(entries, tree.entry(bytes.Bytes.dup(name), tree.KIND_SUBTREE, cid))- }- files.free_buffer(path)- } elif info.kind == stat.KIND_LINK {- val fs2: str.StringView = files.join(dir, str.from_cstr(name_c))- val target_opt = stat.link_target(fs2)- files.free_path(fs2)- if target_opt is some target {- val bid: objid.Id = add_blob_data(tx, target.ptr, target.len)- val kind: u8 = tree.KIND_SYMLINK- @append(entries, tree.entry(bytes.Bytes.dup(name), kind, bid))- @append(new_cache, new_entry(bytes.Bytes.dup(path), info, false, bid))- files.free_buffer(target)- }- files.free_buffer(path)- } else {- val executable: bool = info.executable- val cached = cache_lookup(cache, path)- val reuse: mut bool = false- val target: mut objid.Id = objid.id_none()- if cached is some ce {- if cache_matches(ce, info, executable, now_ms, cache.written_ms) {- target = copy_id(ce.target)- reuse = true- }- }- if !reuse {- val fs3: str.StringView = files.join(dir, str.from_cstr(name_c))- val data_opt = files.read_all(fs3)- files.free_path(fs3)- match data_opt {- some data => {- target = add_blob_data(tx, data.ptr, data.len)- files.free_buffer(data)- }- none => {- failed = true- }- }- }- if !failed {- @append(new_cache, new_entry(bytes.Bytes.dup(path), info, executable, target))- val kind: mut u8 = tree.KIND_FILE- if executable {- kind = tree.KIND_EXECUTABLE- }- @append(entries, tree.entry(bytes.Bytes.dup(name), kind, target))- }- files.free_buffer(path)- }- }- files.free_names(names_list)- files.free_path(dir)-- val out: mut option[objid.Id] = none- if !failed {- if @len(entries) > 0 {- val encoded = tree.encode(entries)- match encoded {- ok body => {- val id: objid.Id = txn.add_object(tx, types.TREE, body)- out = some(copy_id(id))- if id.ptr != none {- val ip: mut ref void = id.ptr as ref void- @free(ip)- }- }- err _ => {- failed = true- }- }- }- }- for e in entries {- if e.name.ptr != none {- val np: mut ref void = e.name.ptr as ref void- @free(np)- }- if e.target.ptr != none {- val tp2: mut ref void = e.target.ptr as ref void- @free(tp2)- }- val ep: mut ref void = e as ref void- @free(ep)- }- @listfree(entries)- if have_old {- tree.free_tree(old)- }- free_local(local, keep)- if failed {- return none- }- return out-}--fn empty_tree_id(tx: mut ref txn.Txn) objid.Id = trust {- val t: tree.Tree = tree.empty()- val encoded = tree.encode(t.entries)- val body: mut bytes.Bytes = bytes.empty()- match encoded {- ok b => {- body = b- }- err _ => {- return objid.id(none)- }- }- val id: objid.Id = txn.add_object(tx, types.TREE, body)- @listfree(t.entries)- return id-}--fn remove_wc_head(v: mut ref view.View, id: objid.Id) void = trust {- viewops.remove_head(v, id)-}--/// Snapshot the working tree into `@`. Returns 0 on success.-pub fn run(repo: layout.Repo) i32 = trust {- val tx_opt = txn.begin(repo)- val tx: mut ref txn.Txn = none- match tx_opt {- some t => {- tx = t- }- none => {- msg.error_prefix()- stdio.eprint("cannot load repository state\n", {})- return 1- }- }-- val st: store.Store = store.open_all(repo)- val wc_opt = viewops.working_copy(tx.view)- val wc: mut objid.Id = objid.id_none()- val have_wc: mut bool = false- if wc_opt is some id {- wc = id- have_wc = true- }-- val cbody: mut bytes.Bytes = bytes.empty()- val c: mut ref commit.Commit = none- val old_tree: mut option[objid.Id] = none- if have_wc {- val body_opt = state.read_body(st.handles, wc, types.COMMIT)- match body_opt {- some b => {- cbody = b- val decoded = commit.decode(cbody)- match decoded {- ok x => {- c = x- old_tree = some(copy_id(c.root_tree))- }- err _ => {- msg.error_prefix()- stdio.eprint("corrupt working-copy commit\n", {})- store.close(st)- txn.abort(tx)- if wc.ptr != none {- val wp: mut ref void = wc.ptr as ref void- @free(wp)- }- return 1- }- }- }- none => {- msg.error_prefix()- stdio.eprint("missing working-copy commit\n", {})- store.close(st)- txn.abort(tx)- if wc.ptr != none {- val wp2: mut ref void = wc.ptr as ref void- @free(wp2)- }- return 1- }- }- }-- val root: str.StringView = layout.root_view(repo)- val rules: mut ignore.Rules = ignore.empty()- ignore.load_root(rules, root)- val cache: Cache = load_cache(repo)- val new_cache: mut list[ref CacheEntry] = lists.new[ref CacheEntry]()- val now_ms: i64 = time.unix_now_millis()- val built = build_dir(- tx,- root,- st.handles,- bytes.empty(),- old_tree,- rules,- cache,- new_cache,- now_ms- )- val new_root: mut objid.Id = objid.id_none()- val build_failed: mut bool = false- match built {- some id => {- new_root = id- }- none => {- if @len(new_cache) > 0 {- // Files were produced before a failure; treat as an error.- build_failed = true- } else {- new_root = empty_tree_id(tx)- }- }- }- if objid.Id.is_none(new_root) && !build_failed {- msg.error_prefix()- stdio.eprint("failed to build working-copy tree\n", {})- build_failed = true- }- if build_failed {- store.close(st)- txn.abort(tx)- if c != none {- commit.free_commit(c)- }- if cbody.ptr != none {- files.free_buffer(cbody)- }- if old_tree is some ot {- if ot.ptr != none {- val op: mut ref void = ot.ptr as ref void- @free(op)- }- }- if wc.ptr != none {- val wp3: mut ref void = wc.ptr as ref void- @free(wp3)- }- ignore.free(rules)- free_cache(cache)- for e in new_cache {- free_entry(e)- }- @listfree(new_cache)- return 1- }-- val unchanged: mut bool = false- if old_tree is some ot2 {- if objid.Id.eql(ot2, new_root) {- unchanged = true- }- }-- if unchanged {- store.close(st)- txn.abort(tx)- if c != none {- commit.free_commit(c)- }- if cbody.ptr != none {- files.free_buffer(cbody)- }- if old_tree is some ot3 {- if ot3.ptr != none {- val op2: mut ref void = ot3.ptr as ref void- @free(op2)- }- }- if wc.ptr != none {- val wp4: mut ref void = wc.ptr as ref void- @free(wp4)- }- if new_root.ptr != none {- val np2: mut ref void = new_root.ptr as ref void- @free(np2)- }- ignore.free(rules)- val sorted: mut Cache = Cache{entries: new_cache, written_ms: now_ms}- sort_cache(sorted.entries)- val _ = save_cache(repo, sorted)- free_cache(cache)- for e in new_cache {- free_entry(e)- }- @listfree(new_cache)- return 0- }-- val committer: prim.Sig = identity.signature(repo)- val author: mut prim.Sig = committer- val parents: mut list[objid.Id] = lists.new[objid.Id]()- val change_id: mut objid.ChangeId = objid.change_id(none)- val message: mut bytes.Bytes = bytes.empty()- if c != none {- author = c.author- for p in c.parents {- @append(parents, copy_id(p))- }- change_id = c.change_id- message = c.message- } else {- val cid: ref u8 = @alloc(16) as ref u8- random.random_bytes(cid as ref void, 16)- change_id = objid.change_id(cid)- }- val renames: list[ref commit.Rename] = lists.new[ref commit.Rename]()- val extra: list[ref prim.KeyValue] = lists.new[ref prim.KeyValue]()- val nc: mut ref commit.Commit = @alloc(@sizeof(commit.Commit)) as ref commit.Commit- nc.version = 1- nc.parents = parents- nc.root_tree = new_root- nc.change_id = change_id- nc.author = author- nc.committer = committer- nc.message = message- nc.renames_state = commit.RENAMES_RECORDED- nc.renames = renames- nc.extra = extra- val encoded: bytes.Bytes = commit.encode(nc)- val new_commit: objid.Id = txn.add_object(tx, types.COMMIT, encoded)- @listfree(nc.parents)- @listfree(nc.renames)- @listfree(nc.extra)- @free(nc as ref void)-- if have_wc {- remove_wc_head(tx.view, wc)- }- viewops.set_workspace(tx.view, new_commit)- viewops.rebuild_heads(tx.view)-- val status: i32 = txn.finish(tx, bytes.bytes(c"snapshot", 8))- if status == 0 {- val _ = gitmap.mark_native(repo, new_commit)- }- store.close(st)- if c != none {- commit.free_commit(c)- }- if cbody.ptr != none {- files.free_buffer(cbody)- }- if old_tree is some ot4 {- if ot4.ptr != none {- val op3: mut ref void = ot4.ptr as ref void- @free(op3)- }- }- if wc.ptr != none {- val wp5: mut ref void = wc.ptr as ref void- @free(wp5)- }- if new_root.ptr != none {- val np3: mut ref void = new_root.ptr as ref void- @free(np3)- }- if new_commit.ptr != none {- val cp2: mut ref void = new_commit.ptr as ref void- @free(cp2)- }- identity.free_sig(committer)- // Author/message/change ID fields borrowed from the old commit body (freed- // above) or the freshly allocated random ID.- if c == none && change_id.ptr != none {- val cip: mut ref void = change_id.ptr as ref void- @free(cip)- }- ignore.free(rules)- if status == 0 {- val sorted2: mut Cache = Cache{entries: new_cache, written_ms: now_ms}- sort_cache(sorted2.entries)- val _ = save_cache(repo, sorted2)- }- free_cache(cache)- for e in new_cache {- free_entry(e)- }- @listfree(new_cache)- return status-}--- a/src/sx.lock+++ /dev/null@@ -1,1 +0,0 @@-version "1"--- a/src/sx.mod+++ /dev/null@@ -1,20 +0,0 @@-entry "./src/main.sx"-version "v0.0.1"-spectre_version "v0.0.18"--build release {- action "mkdir -p $OUT && ./build-native.sh $OUT && spectre ./src/main.sx -release -link-obj:$OUT/veins_native.o -o ./vn"- flags "-release"- output "./vn"- windows {- output "vn.exe"- }-}--build dev {- action "mkdir -p $OUT && ./build-native.sh $OUT && spectre ./src/main.sx -link-obj:$OUT/veins_native.o -o ./vn-dev"- output "./vn-dev"- windows {- output "vn-dev.exe"- }-}--- /dev/null+++ b/veins/.gitignore@@ -0,0 +1,9 @@+vn-dev+vn+veins-dev+SPECTRE_LANGUAGE_REFERENCE.md+lib/+std__*+s-out/+docs-out*/+.sxb/--- /dev/null+++ b/veins/build-native.sh@@ -0,0 +1,32 @@+#!/bin/sh+# Build the native hot-path objects and combine them for spectre -link-obj.+set -e++out="${1:-.sxb/linux.x86_64}"+cc="${CC:-cc}"+mkdir -p "$out"++crypto="src/crypto"+b3="$crypto/blake3"++"$cc" -O3 -c "$crypto/blake3_c.c" -o "$out/blake3_c.o"+"$cc" -O3 -c "$b3/blake3.c" -o "$out/blake3_impl.o"+"$cc" -O3 -c "$b3/blake3_dispatch.c" -o "$out/blake3_dispatch.o"+"$cc" -O3 -c "$b3/blake3_portable.c" -o "$out/blake3_portable.o"+"$cc" -O3 -msse2 -c "$b3/blake3_sse2.c" -o "$out/blake3_sse2.o"+"$cc" -O3 -msse4.1 -c "$b3/blake3_sse41.c" -o "$out/blake3_sse41.o"+"$cc" -O3 -mavx2 -c "$b3/blake3_avx2.c" -o "$out/blake3_avx2.o"+"$cc" -O3 -mavx512f -mavx512vl -c "$b3/blake3_avx512.c" -o "$out/blake3_avx512.o"+"$cc" -O3 -c "src/chunking/fastcdc_c.c" -o "$out/fastcdc_c.o"++"$cc" -r \+ "$out/blake3_c.o" \+ "$out/blake3_impl.o" \+ "$out/blake3_dispatch.o" \+ "$out/blake3_portable.o" \+ "$out/blake3_sse2.o" \+ "$out/blake3_sse41.o" \+ "$out/blake3_avx2.o" \+ "$out/blake3_avx512.o" \+ "$out/fastcdc_c.o" \+ -o "$out/veins_native.o"--- /dev/null+++ b/veins/src/chunking/fastcdc.sx@@ -0,0 +1,41 @@+/// 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")++extern (C) fn vn_fastcdc_next(data: ref u8, len: usize, gear: ref u8) usize = "vn_fastcdc_next"++pub val (+ MIN_SIZE: usize = 16384+ AVG_SIZE: usize = 65536+ MAX_SIZE: usize = 262144+ NORMALIZATION: usize = 2+)++/// 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 = trust {+ pre {+ progress: len > 0+ }+ return vn_fastcdc_next(data, len, gear.GEAR_RAW)+}++/// Split a byte span into chunk lengths.+pub fn split(data: ref u8, len: usize) list[usize] = trust {+ val out: mut list[usize] = lists.new[usize]()+ val off: mut usize = 0+ for off < len {+ val n: usize = next_len(@ptradd(data, off as i64), len - off)+ @append(out, n)+ off = off + n+ }+ return out+}--- /dev/null+++ b/veins/src/chunking/fastcdc_c.c@@ -0,0 +1,39 @@+/* FastCDC next-chunk scan used by the format's chunker. */++#include <stddef.h>+#include <stdint.h>+#include <string.h>++#define VN_CDC_MIN 16384+#define VN_CDC_AVG 65536+#define VN_CDC_MAX 262144+#define VN_CDC_MASK_S 0x3ffffULL+#define VN_CDC_MASK_L 0x3fffULL++static uint64_t gear_at(const uint8_t *gear, uint8_t c) {+ uint64_t v;+ memcpy(&v, gear + (size_t)c * 8, sizeof(v));+ return v;+}++size_t vn_fastcdc_next(const uint8_t *data, size_t len, const uint8_t *gear) {+ if (len <= VN_CDC_MIN) {+ return len;+ }+ size_t limit = len < VN_CDC_MAX ? len : VN_CDC_MAX;+ size_t normal = VN_CDC_AVG < limit ? VN_CDC_AVG : limit;+ uint64_t fp = 0;+ for (size_t i = VN_CDC_MIN; i < normal; i++) {+ fp = (fp >> 1) + gear_at(gear, data[i]);+ if ((fp & VN_CDC_MASK_S) == 0) {+ return i + 1;+ }+ }+ for (size_t i = normal; i < limit; i++) {+ fp = (fp >> 1) + gear_at(gear, data[i]);+ if ((fp & VN_CDC_MASK_L) == 0) {+ return i + 1;+ }+ }+ return limit;+}Binary files a/veins/src/chunking/gear.bin and b/veins/src/chunking/gear.bin differ--- /dev/null+++ b/veins/src/chunking/gear.sx@@ -0,0 +1,78 @@+/// FastCDC gear table for veins format version 1.+///+/// The 256 entries are derived deterministically, so that independent+/// implementations can reproduce them:+///+/// gear[i] = u64le(BLAKE3("veins/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 = [+ 0xf8447b379cdadcd5, 0xbe63d125aec8ca6d, 0x10bcf6f7c33cbed3, 0x2b6ba7e5a572be1b,+ 0x145ba610bca60ff6, 0x335db29c88ea2545, 0xaf7ab78b34ea1c8f, 0x04383fe20dcbf16a,+ 0x542c3ed8a305a2e4, 0x8306bb8ba52f1966, 0x64abea4024164cb2, 0xd5d28a2763a5c906,+ 0xa709f38738243984, 0x0a1ac1c77c75aa83, 0x2fe3df4653145470, 0x8ef53a2c653fab0e,+ 0xe6f0c2e4436fe0b0, 0xf387dc66d595a4fd, 0xd520313dc5c2ef0c, 0x3aa4df70dc7b4e20,+ 0xfe89fa05b2229b26, 0xd5b811960c27b302, 0xd6b9a82445390552, 0x8c9df4eb17abefbb,+ 0x8dddfb83b6f3e3f5, 0x0dfd5490314a4a77, 0xcd39d37f4fffeb07, 0xd953ec046f403aef,+ 0xfd67339f7fb60679, 0x1673126b2d34af03, 0x810365172ff5c83f, 0x2e219c15c03a0ce6,+ 0xcd2dd776c4dc8b37, 0x31a05022f6757ac7, 0xa54aaac64e2b7a4f, 0x541cc9dbe8ef6090,+ 0x15f25ab7ac626796, 0x6a8743338a21c0db, 0x15856273cdeb225b, 0x92d3b90d24b0ceab,+ 0xdb7ed64743e6bafd, 0x6a2371fe5845980b, 0x3ed2cbd1a12b1554, 0x26292f185e7ae5c2,+ 0xcfa468695ae32b7c, 0x10c8ad9d7d37b38b, 0x0c93c73c9b8a5760, 0xdce731099879e3ac,+ 0x948f5e10a859b0f9, 0x5b7b5381c2b61ad3, 0x032e2bccef396ec0, 0xcb04960d80779661,+ 0x1800187b89406bba, 0x8cfeb1e5741f9b5b, 0xc0a8b6dd4ca2bc72, 0x7121d98743aad057,+ 0x62122a734c7c30cf, 0x09dfc78344470469, 0x7dd2e6c3164e95cc, 0x1e081af5098f9f95,+ 0xa060c1359428a17a, 0xfbbf087daa942d8d, 0x02befbb34a59cfa0, 0xf61aba2e56e7fcab,+ 0xd201b08ba97b4f74, 0x05d1923c598bb943, 0x577cb1ac90c58fdc, 0x35714370655de214,+ 0x9e875d6330c98d09, 0x580e31b7e5d121d1, 0x86e331d3a1868867, 0x7198d317f173adfc,+ 0xd1d712f288f8f74f, 0x498eb6b5efeca820, 0x01609a0433de3ce6, 0xc6451604d3e5a30e,+ 0x7cb8c805a7fc71d4, 0xabd48608b949d705, 0x80a7504b42991b37, 0xde2d8d960bc877d9,+ 0x6658840c7b5680c4, 0x90ff0a9f74a67da4, 0x9c44badf508da6b7, 0x9399bf790bbe7784,+ 0x984ef4f5cd8b44d9, 0x338a088febb6b2c4, 0x56b6457eba02a001, 0x69db87f3d877bc17,+ 0xeaa4df254010fc26, 0xd4c46364dcfcc4c7, 0xf5f5ffa312012d68, 0xd56c6fd2995b3e2d,+ 0x098e8ef0f3185a71, 0xd57d7c0096690b41, 0xd562d821200e0cd4, 0xbfba257d5a89b160,+ 0x1058a4dfeffa765d, 0x74a5f76a74e5ca3c, 0xbcf278dd8ff805dc, 0x13696b2e934dd66f,+ 0xa8e2ffed5d6c8f52, 0xc9711402212f8271, 0x83db1ae9a24b47f4, 0xfec127f15e6c1470,+ 0x6e8185b3a8e5e1fc, 0xd503ce1f19ca76f8, 0x5e80dadee3f2c38a, 0x2d1ff7b2e1cb7079,+ 0xf572fb19e969ef53, 0x502708c0febdf28c, 0x59f0859c330bd3ae, 0xfefb158359b5411f,+ 0xbcbcce46e6c1b56d, 0x9fc6bd49258ef328, 0x89d3b5d6ba11aa7c, 0x4e44ee7a780f8aa6,+ 0xcca6584b41c6a8dd, 0xbd39bf6f976088f1, 0x609df3f5f267e2cf, 0x970c32cd9b8f1f95,+ 0x373a464e80f4734b, 0xfd01ca133c483c61, 0x317dfec1e4e54486, 0x653bb090e32d5fb8,+ 0x0944739599bfa481, 0x33ee31072ab56364, 0xd3826c26bc20b44c, 0xd11f9251c67a66ac,+ 0x79a81cf24d93662f, 0x9672efb77cb79214, 0x0b6852062b150542, 0x22cb8254926d5d21,+ 0xf68817c5be91619e, 0x1fb235ed20504b6c, 0x7a00398632aae3d8, 0xd5cafd4331978a29,+ 0xf80e0a5957bca856, 0x409ce1b813206914, 0xd0f1da7e99289a41, 0x2ede97d8000af47b,+ 0x6a27ef6571d9b969, 0x97c4695b34247b16, 0x5ee4b2b0e7919e12, 0x73f02023b038ceed,+ 0x54e24747c8dbc3f2, 0xea175f09cd4ea419, 0xa420b4e91e595736, 0xf58072b7aa16c147,+ 0xc4eed8a665f16537, 0xefe95010907b5c71, 0x20b530bfb2fb6c5d, 0xa14f7dca9de676bd,+ 0x899835e7943ffc24, 0x72cea269e19c9b60, 0xa2311c0586c3c70d, 0x5feb4a14932c2e90,+ 0xbf24d7cf401f1a8c, 0xae081fd9aa06845a, 0x332ce9fca6bbb7df, 0xc4c0c4d9b89e0df2,+ 0x2bddbc99fe5fb745, 0x533b9037add81672, 0x133ac755cf098a00, 0x8305c21cea592a03,+ 0x2164728763c1f742, 0x8385d8702b7a940a, 0xb8b02364b0352c47, 0xd5535761e27bae91,+ 0x930b49bf6552198f, 0xccd2c5d2f32ab8c6, 0x58c74b4b32fc9fa8, 0x98a324c44c1cd723,+ 0x2abeecf0cfc735fc, 0x6419bb9739226916, 0xd9e94c1946307dd2, 0xe15622a475f6e038,+ 0xc48fba22892a33bc, 0x0722a604b075bafc, 0x78889b342ff4560c, 0xdada1d3833b35bd6,+ 0x4917f2c07311a5cc, 0x9d7685084873a92a, 0x5869edb9c4b4e78c, 0x30afc030f9d64382,+ 0x548ed28c8845626f, 0x606be35894cbee13, 0xaaa4a0c60695574f, 0x364cf234a3dd2844,+ 0x9aba0e81ff2f109c, 0x18d1e9b3fdfda42c, 0x1b9477ec5fb1ad36, 0x7f0136e7d6a3cb98,+ 0x9a4e7496f95a6fbc, 0xb940293ab845abd6, 0xa1c6388ef0208374, 0x8da07493e7de1f8a,+ 0xeeba605e6e273c4c, 0x3202537c27f4c285, 0xc40eebd30f194254, 0xdb3e091b83f3578b,+ 0xef4d4e9267b4c82e, 0xce163a6c0f695d0d, 0x0b73d109498e2d9a, 0xb0ecccc0a05090a8,+ 0x4748b37a01cd7c50, 0x75bedfaf04e09117, 0x4290c117203c922a, 0x0f4edf02e3d62367,+ 0x9f88f3082a0860ef, 0x029e5bb038f506fa, 0xb4ff698bcd73d0ac, 0x61321d4822b1ebb9,+ 0x997b0a0bfcbc4b7e, 0x669e117eb2fbc329, 0xc770e6b51cf723e1, 0x43e9c64d4ceba4fa,+ 0x7089a98e8a61f669, 0x7635f6b39edd3638, 0x7efb2ec180815b1a, 0x599b9ba270412abe,+ 0x099db42c6da84f07, 0xa80aa895e988a9e2, 0x857538709775368c, 0x0f35b67029f03082,+ 0x29d1d07f6cdff719, 0x25f0c392a5184c13, 0xfab7c93869e72670, 0x57bfb01577cf7ea5,+ 0xf243888561a284c9, 0x2cb309bd1f1e4f95, 0x860339add5cde62f, 0xb5c77be90a3bab2a,+ 0x016359c3a034ab67, 0xf4426de9276d41b1, 0x1f0f25a49fb35408, 0xa216f9fe7f9a47d4,+ 0xdf6ff4f9bc47eb4e, 0xde377b438cddb110, 0xa2bf999d31ef328f, 0x460eea338ffb2e84,+ 0xf73ea9dde1297fa3, 0x05cb4964fec1213c, 0x7713be29f105fd3e, 0x6d6796f838c38ba2,+ 0x8c8adb1031c0ae50, 0x526a7f116fe65583, 0xeabdacfe2ef6c020, 0x1c0de4493237857f,+ 0xac655048637e992b, 0x2664f2bf04599664, 0x5cbe9c160f2f8c53, 0x1cc056978d12a1dc,+ 0x889e35cb2ca6742f, 0xe0ab4043f6b783cc, 0x011128d888973e10, 0xfb74bdcd0afb54eb,+]++/// Byte view of the frozen table for fast FFI-free indexing.+pub val GEAR_RAW: ref u8 = @embed("gear.bin")--- /dev/null+++ b/veins/src/cli/bench_cmd.sx@@ -0,0 +1,210 @@+/// Benchmark-only lazy import probe using the git CLI backend.++val str = use("std/string")+val stdio = use("std/stdio")+val msg = use("../core/msg.sx")+val time = use("std/time")+val bytes = use("../core/bytes.sx")+val buf = use("../core/buf.sx")+val idmap = use("../store/idmap.sx")+val files = use("../io/files.sx")++extern (C) fn popen(cmd: ref u8, mode: ref u8) ref void = "popen"+extern (C) fn pclose(stream: ref void) i32 = "pclose"+extern (C) fn fread(ptr: ref void, size: usize, n: usize, stream: ref void) usize = "fread"+extern (C) fn memchr(s: ref void, c: i32, n: usize) ref void = "memchr"++fn find_raw(p: ref u8, start: usize, end: usize, target: u8) usize = trust {+ if start >= end {+ return end+ }+ val hit: ref void = memchr(+ @ptradd(p, start as i64) as ref void,+ target as i32,+ end - start+ )+ if hit == none {+ return end+ }+ return @bitcast(hit, usize) - @bitcast(p, usize)+}++fn parse_size_raw(p: ref u8, start: usize, end: usize) usize = trust {+ val n: mut usize = 0+ val i: mut usize = start+ for i < end {+ val c: u8 = @load8(@ptradd(p, i as i64))+ if c < 48 || c > 57 {+ break+ }+ n = n * 10 + (c - 48) as usize+ i+++ }+ return n+}++fn eq_raw(p: ref u8, start: usize, text: ref u8, n: usize) bool = trust {+ val i: mut usize = 0+ for i < n {+ if @load8(@ptradd(p, (start + i) as i64)) != @load8(@ptradd(text, i as i64)) {+ return false+ }+ i+++ }+ return true+}++fn capture(cmd: ref u8, out: mut buf.Buf) bool = trust {+ val pipe = popen(cmd, c"r")+ if pipe == none {+ return false+ }+ val chunk: ref u8 = @alloc(65536) as ref u8+ for {+ val n: usize = fread(chunk as ref void, 1, 65536, pipe)+ if n == 0 {+ break+ }+ buf.Buf.put_raw(out, chunk, n)+ }+ @free(chunk as ref void)+ pclose(pipe)+ return true+}++pub fn run(args: list[ref u8], start: usize) i32 = trust {+ if start >= @len(args) {+ msg.error_prefix()+ stdio.eprint("bench-import requires a git directory\n", {})+ return 1+ }+ val repo_arg = @get(args, start)+ val repo: mut str.StringView = str.from_cstr(c".")+ if repo_arg is some r {+ repo = str.from_cstr(r)+ }+ val repo_view: str.StringView = repo+ val t0: i64 = time.now_ns()++ val listing: mut buf.Buf = buf.new(1048576)+ val list_cmd: ref u8 = @fmtalloc(+ "git --git-dir={s} rev-list --objects --all --filter=blob:none",+ {repo_view}+ )+ val listed: bool = capture(list_cmd, listing)+ @free(list_cmd as ref void)+ if !listed {+ buf.Buf.free(listing)+ msg.error_prefix()+ stdio.eprint("cannot run git rev-list\n", {})+ return 1+ }++ val meta_buf: mut buf.Buf = buf.new(65536)+ val lp: ref u8 = listing.ptr+ val llen: usize = listing.len+ val pos: mut usize = 0+ for pos < llen {+ val eol: usize = find_raw(lp, pos, llen, 10)+ val end: usize = find_raw(lp, pos, eol, 32)+ if end > pos {+ buf.Buf.put_raw(meta_buf, @ptradd(lp, pos as i64), end - pos)+ buf.Buf.put_u8(meta_buf, 10)+ }+ pos = eol + 1+ }+ buf.Buf.free(listing)++ val meta_path: ref u8 = @fmtalloc("/tmp/veins-bench-meta-{d}.oids", {time.now_ns()})+ val meta_view: str.StringView = str.from_cstr(meta_path)+ val meta_written: bool = files.write_all(meta_view, buf.Buf.view(meta_buf))+ buf.Buf.free(meta_buf)+ if !meta_written {+ @free(meta_path as ref void)+ msg.error_prefix()+ stdio.eprint("cannot write temporary commit/tree list\n", {})+ return 1+ }++ val data: mut buf.Buf = buf.new(1048576)+ val batch_cmd: ref u8 = @fmtalloc(+ "git --git-dir={s} cat-file --batch < {s}",+ {repo_view, meta_view}+ )+ val batched: bool = capture(batch_cmd, data)+ @free(batch_cmd as ref void)+ if !batched {+ buf.Buf.free(data)+ files.delete(meta_view)+ @free(meta_path as ref void)+ msg.error_prefix()+ stdio.eprint("cannot run git cat-file --batch\n", {})+ return 1+ }++ val key: ref u8 = @alloc(32) as ref u8+ @memcpy(key as ref void, c"veins-gitoid", 12)+ val lazy: mut idmap.IdSet = idmap.new(16384)+ val commits: mut usize = 0+ val trees: mut usize = 0+ val entries: mut usize = 0+ val lazy_count: mut usize = 0++ val dp: ref u8 = data.ptr+ val dlen: usize = data.len+ val p: mut usize = 0+ for p < dlen {+ val nl: usize = find_raw(dp, p, dlen, 10)+ val sp1: usize = find_raw(dp, p, nl, 32)+ val sp2: usize = find_raw(dp, sp1 + 1, nl, 32)+ val size: usize = parse_size_raw(dp, sp2 + 1, nl)+ val body_start: usize = nl + 1+ val body_end: usize = body_start + size+ val kind_len: usize = sp2 - sp1 - 1++ if kind_len == 6 && eq_raw(dp, sp1 + 1, c"commit", 6) {+ commits+++ } elif kind_len == 4 && eq_raw(dp, sp1 + 1, c"tree", 4) {+ trees+++ val ep: mut usize = body_start+ for ep < body_end {+ val space: usize = find_raw(dp, ep, body_end, 32)+ val nul: usize = find_raw(dp, space + 1, body_end, 0)+ val oid_start: usize = nul + 1+ if oid_start + 20 > body_end {+ break+ }+ val mode_len: usize = space - ep+ val is_blob: bool = mode_len == 6+ && @load8(@ptradd(dp, ep as i64)) == 49+ && (@load8(@ptradd(dp, (ep + 1) as i64)) == 48+ || @load8(@ptradd(dp, (ep + 1) as i64)) == 50)+ if is_blob {+ @memcpy(+ @ptradd(key, 12) as ref void,+ @ptradd(dp, oid_start as i64) as ref void,+ 20+ )+ if idmap.put(lazy, bytes.bytes(key, 32)) {+ lazy_count+++ }+ }+ entries+++ ep = oid_start + 20+ }+ }+ p = body_end + 1+ }+ idmap.free(lazy)+ @free(key as ref void)+ buf.Buf.free(data)+ files.delete(meta_view)+ @free(meta_path as ref void)++ val ms: i64 = (time.now_ns() - t0) / 1000000+ stdio.print(+ "commits={d} trees={d} tree_entries={d} lazy_blobs={d} total={d}ms\n",+ {commits, trees, entries, lazy_count, ms}+ )+ return 0+}--- /dev/null+++ b/veins/src/cli/checkout_cmd.sx@@ -0,0 +1,31 @@+/// `vn checkout [rev]`: materialize a revision into the working directory.++val str = use("std/string")+val stdio = use("std/stdio")+val msg = use("../core/msg.sx")+val bytes = use("../core/bytes.sx")+val layout = use("../store/layout.sx")+val checkout = use("../worktree/checkout.sx")++pub fn run(args: list[ref u8], start: usize) i32 = trust {+ val rev: mut bytes.Bytes = bytes.empty()+ if start < @len(args) {+ val r_opt = @get(args, start)+ if r_opt is some r {+ rev = bytes.from_cstr(r)+ }+ }+ val repo_opt = layout.discover(str.from_cstr(c"."))+ match repo_opt {+ some repo => {+ val status: i32 = checkout.run(repo, rev)+ layout.free_repo(repo)+ return status+ }+ none => {+ msg.error_prefix()+ stdio.eprint("not a veins repository\n", {})+ return 1+ }+ }+}--- /dev/null+++ b/veins/src/cli/diff_cmd.sx@@ -0,0 +1,302 @@+/// `vn diff [-r <rev>]`: show a unified diff.++val str = use("std/string")+val stdio = use("std/stdio")+val msg = use("../core/msg.sx")+val bytes = use("../core/bytes.sx")+val lists = use("../core/lists.sx")+val objid = use("../object/id.sx")+val tree = use("../object/tree.sx")+val view = use("../object/view.sx")+val graph = use("../object/graph.sx")+val treediff = use("../object/treediff.sx")+val treewalk = use("../object/treewalk.sx")+val content = use("../object/content.sx")+val store = use("../store/store.sx")+val state = use("../store/state.sx")+val layout = use("../store/layout.sx")+val viewops = use("../store/viewops.sx")+val files = use("../io/files.sx")+val object = use("../git/object.sx")+val snapshot = use("../worktree/snapshot.sx")++type DiffOp = {+ tag: mut u8+ ai: mut usize+ bi: mut usize+}++pub type GitSource = {+ repo: mut object.GitRepo+ open: mut bool+}++pub fn open_git(repo: layout.Repo) GitSource = trust {+ val p: str.StringView = layout.git_dir(repo)+ val r = object.open(p)+ files.free_path(p)+ val g: mut GitSource = GitSource{repo: @zeroed, open: false}+ match r {+ ok x => {+ g.repo = x+ g.open = true+ }+ err _ => {+ }+ }+ return g+}++pub fn close_git(g: mut GitSource) void = trust {+ if g.open {+ object.free(g.repo)+ g.open = false+ }+}++fn contains_nul(data: bytes.Bytes) bool = trust {+ val n: usize = data.len+ val limit: usize = 8192+ val i: mut usize = 0+ for i < n && i < limit {+ if bytes.Bytes.at(data, i) == 0 {+ return true+ }+ i+++ }+ return false+}++fn split_lines(data: bytes.Bytes) list[bytes.Bytes] = trust {+ val out: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()+ if data.len == 0 {+ return out+ }+ val start: mut usize = 0+ val i: mut usize = 0+ for i <= data.len {+ val at_end: bool = i == data.len+ if at_end || bytes.Bytes.at(data, i) == 10 {+ if i > start || !at_end || bytes.Bytes.at(data, i - 1) != 10 {+ @append(out, bytes.Bytes.slice(data, start, i))+ }+ start = i + 1+ }+ i+++ }+ return out+}++fn render_one(+ handles: list[ref store.Handle],+ git: ref GitSource,+ change: ref treediff.Change+) void = trust {+ val path_view = str.view(change.path.ptr, change.path.len as i64)+ if change.new_kind == tree.KIND_CONFLICT {+ stdio.print("Conflict: {s}\n", {path_view})+ return+ }+ val old_data: mut bytes.Bytes = bytes.empty()+ val new_data: mut bytes.Bytes = bytes.empty()+ val old_owned: mut bool = false+ val new_owned: mut bool = false+ if change.old_kind != treewalk.KIND_MISSING {+ val o = content.read_blob(handles, change.old_id, git.repo, git.open)+ if o is some d {+ old_data = d+ old_owned = true+ }+ }+ if change.new_kind != treewalk.KIND_MISSING {+ val n = content.read_blob(handles, change.new_id, git.repo, git.open)+ if n is some d {+ new_data = d+ new_owned = true+ }+ }+ if contains_nul(old_data) || contains_nul(new_data) {+ stdio.print("Binary files a/{s} and b/{s} differ\n", {path_view, path_view})+ } else {+ stdio.print("--- ", {})+ if change.old_kind == treewalk.KIND_MISSING {+ stdio.print("/dev/null", {})+ } else {+ stdio.print("a/{s}", {path_view})+ }+ stdio.print("\n+++ ", {})+ if change.new_kind == treewalk.KIND_MISSING {+ stdio.print("/dev/null", {})+ } else {+ stdio.print("b/{s}", {path_view})+ }+ stdio.print("\n", {})+ val a = split_lines(old_data)+ val b = split_lines(new_data)+ val a_count: usize = @len(a)+ val b_count: usize = @len(b)+ val a_start: mut usize = 1+ if a_count == 0 {+ a_start = 0+ }+ val b_start: mut usize = 1+ if b_count == 0 {+ b_start = 0+ }+ stdio.print("@@ -{d},{d} +{d},{d} @@\n", {a_start, a_count, b_start, b_count})+ val ai: mut usize = 0+ for ai < a_count {+ val line = line_at(a, ai)+ stdio.print("-{s}\n", {str.view(line.ptr, line.len as i64)})+ ai+++ }+ val bi: mut usize = 0+ for bi < b_count {+ val line2 = line_at(b, bi)+ stdio.print("+{s}\n", {str.view(line2.ptr, line2.len as i64)})+ bi+++ }+ @listfree(a)+ @listfree(b)+ }+ if old_owned {+ files.free_buffer(old_data)+ }+ if new_owned {+ files.free_buffer(new_data)+ }+}++pub fn render(+ handles: list[ref store.Handle],+ git: mut GitSource,+ old_tree: option[objid.Id],+ new_tree: option[objid.Id]+) void = trust {+ val changes = treediff.compare(handles, old_tree, new_tree)+ for c in changes {+ render_one(handles, git, c)+ }+ treediff.free(changes)+}++fn list_bytes(xs: list[bytes.Bytes], i: usize) bytes.Bytes = trust {+ val o = @get(xs, i)+ if o is some b {+ return b+ }+ return bytes.empty()+}++fn tree_of(handles: list[ref store.Handle], id: objid.Id) option[objid.Id] = trust {+ val lc_opt = graph.load_commit(handles, id)+ val out: mut option[objid.Id] = none+ if lc_opt is some lc {+ out = some(graph.copy_id(lc.c.root_tree))+ graph.free_loaded(lc)+ }+ return out+}++fn parent_tree_of(handles: list[ref store.Handle], id: objid.Id) option[objid.Id] = trust {+ val lc_opt = graph.load_commit(handles, id)+ val out: mut option[objid.Id] = none+ if lc_opt is some lc {+ if @len(lc.c.parents) > 0 {+ val p = @get(lc.c.parents, 0)+ if p is some pid {+ val t = tree_of(handles, pid)+ if t is some tid {+ out = some(tid)+ }+ }+ }+ graph.free_loaded(lc)+ }+ return out+}++fn free_tree_opt(t: option[objid.Id]) void = trust {+ if t is some id {+ if id.ptr != none {+ val p: mut ref void = id.ptr as ref void+ @free(p)+ }+ }+}++pub fn run(repo: layout.Repo, revs: list[bytes.Bytes]) i32 = trust {+ val snap: i32 = snapshot.run(repo)+ if snap != 0 {+ return snap+ }+ val st: store.Store = store.open_all(repo)+ val v_opt = state.current_view(repo, st.handles)+ val v: mut ref view.View = none+ match v_opt {+ some x => {+ v = x+ }+ none => {+ store.close(st)+ msg.error_prefix()+ stdio.eprint("no operation state\n", {})+ return 1+ }+ }+ val old_tree: mut option[objid.Id] = none+ val new_tree: mut option[objid.Id] = none+ val status: mut i32 = 0+ if @len(revs) >= 2 {+ val a: bytes.Bytes = list_bytes(revs, 0)+ val b: bytes.Bytes = list_bytes(revs, 1)+ val ra = graph.resolve(st.handles, v, a)+ val rb = graph.resolve(st.handles, v, b)+ if ra is some ia {+ old_tree = tree_of(st.handles, ia)+ } else {+ status = 1+ }+ if rb is some ib {+ new_tree = tree_of(st.handles, ib)+ } else {+ status = 1+ }+ } elif @len(revs) == 1 {+ val a: bytes.Bytes = list_bytes(revs, 0)+ val ra = graph.resolve(st.handles, v, a)+ if ra is some ia {+ old_tree = parent_tree_of(st.handles, ia)+ new_tree = tree_of(st.handles, ia)+ } else {+ status = 1+ }+ } else {+ val wc_opt = viewops.working_copy(v)+ if wc_opt is some wc {+ old_tree = parent_tree_of(st.handles, wc)+ new_tree = tree_of(st.handles, wc)+ }+ }+ if status != 0 {+ msg.error_prefix()+ stdio.eprint("unknown revision\n", {})+ } else {+ val git: mut GitSource = open_git(repo)+ render(st.handles, git, old_tree, new_tree)+ close_git(git)+ }+ free_tree_opt(old_tree)+ free_tree_opt(new_tree)+ view.free_view(v)+ store.close(st)+ return status+}++fn line_at(ls: list[bytes.Bytes], i: usize) bytes.Bytes = {+ val o = @get(ls, i)+ if o is some l {+ return l+ }+ return bytes.empty()+}--- /dev/null+++ b/veins/src/cli/fsck_cmd.sx@@ -0,0 +1,23 @@+/// `vn fsck`: verify the repository.++val str = use("std/string")+val stdio = use("std/stdio")+val msg = use("../core/msg.sx")+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 => {+ msg.error_prefix()+ stdio.eprint("not a veins repository: {s}\n", {path})+ }+ }+ return status+}--- /dev/null+++ b/veins/src/cli/git_cmd.sx@@ -0,0 +1,123 @@+/// `vn git`: the git bridge. M1 provides `import`.++val str = use("std/string")+val bytes = use("../core/bytes.sx")+val stdio = use("std/stdio")+val msg = use("../core/msg.sx")+val layout = use("../store/layout.sx")+val mirror = use("../git/mirror.sx")+val import = use("../git/import.sx")+val export = use("../git/export.sx")++pub fn run(args: list[ref u8], start: usize) i32 = trust {+ val sub_opt = @get(args, start)+ val sub: mut ref u8 = none+ match sub_opt {+ some s => {+ sub = s+ }+ none => {+ msg.error_prefix()+ stdio.eprint("expected a git subcommand (import)\n", {})+ return 1+ }+ }+ if @strcmp(sub, c"import") == 0 {+ return run_import(args, start + 1)+ }+ if @strcmp(sub, c"export") == 0 {+ return run_export(args, start + 1)+ }+ msg.error_prefix()+ stdio.eprint("unknown git subcommand: {s}\n", {str.from_cstr(sub)})+ return 1+}++fn run_import(args: list[ref u8], start: usize) i32 = trust {+ val repo_path: mut str.StringView = str.from_cstr(c".")+ val source: mut option[str.StringView] = none+ val i: mut usize = start+ for i < @len(args) {+ val arg_opt = @get(args, i)+ if arg_opt is some a {+ val av: bytes.Bytes = bytes.from_cstr(a)+ val prefix: bytes.Bytes = bytes.bytes(c"-source:", 8)+ if bytes.Bytes.starts_with(av, prefix) {+ if av.len == 8 {+ msg.error_prefix()+ stdio.eprint("-source: requires a path\n", {})+ return 1+ }+ val value: bytes.Bytes = bytes.Bytes.slice(av, 8, av.len)+ source = some str.view(value.ptr, value.len as i64)+ } elif av.len > 0 && bytes.Bytes.at(av, 0) == 45 {+ msg.error_prefix()+ stdio.eprint("unknown flag: {s}\n", {str.from_cstr(a)})+ return 1+ } else {+ repo_path = str.from_cstr(a)+ }+ i+++ } else {+ i+++ }+ }+ val repo_opt = layout.discover(repo_path)+ val repo: mut layout.Repo = layout.Repo{root: @zeroed}+ match repo_opt {+ some r => {+ repo = r+ }+ none => {+ msg.error_prefix()+ stdio.eprint("not a veins repository: {s}\n", {repo_path})+ return 1+ }+ }+ if source is some src {+ val prepared = mirror.prepare(repo, src)+ if prepared != 0 {+ msg.error_prefix()+ stdio.eprint("cannot prepare git mirror (code {d})\n", {prepared})+ layout.free_repo(repo)+ return 1+ }+ }+ val status: i32 = import.run(repo)+ layout.free_repo(repo)+ return status+}+++fn run_export(args: list[ref u8], start: usize) i32 = trust {+ val repo_path: mut str.StringView = str.from_cstr(c".")+ val i: mut usize = start+ for i < @len(args) {+ val arg_opt = @get(args, i)+ if arg_opt is some a {+ val av: bytes.Bytes = bytes.from_cstr(a)+ if av.len > 0 && bytes.Bytes.at(av, 0) == 45 {+ msg.error_prefix()+ stdio.eprint("unknown flag: {s}\n", {str.from_cstr(a)})+ return 1+ }+ repo_path = str.from_cstr(a)+ }+ i+++ }+ val repo_opt = layout.discover(repo_path)+ val repo: mut layout.Repo = layout.Repo{root: @zeroed}+ match repo_opt {+ some r => {+ repo = r+ }+ none => {+ msg.error_prefix()+ stdio.eprint("not a veins repository: {s}\n", {repo_path})+ return 1+ }+ }+ val status: i32 = export.run(repo)+ layout.free_repo(repo)+ return status+}--- /dev/null+++ b/veins/src/cli/help_cmd.sx@@ -0,0 +1,279 @@+/// `vn help`: show usage for the program or one of its commands.++val str = use("std/string")+val stdio = use("std/stdio")+val msg = use("../core/msg.sx")++fn cmd_is(a: ref u8, text: ref u8, len: usize) bool = trust {+ return str.eql(str.from_cstr(a), str.view(text, len as i64))+}++pub fn usage() void = trust {+ stdio.puts("veins is a tool for managing source code")+ stdio.puts("")+ stdio.puts("commands:")+ stdio.puts(" init create a repository")+ stdio.puts(" git import from or export to git")+ stdio.puts(" checkout write a revision into the working directory")+ stdio.puts(" status show working-copy changes")+ stdio.puts(" log show commit history")+ stdio.puts(" diff show a unified diff")+ stdio.puts(" new start a new change")+ stdio.puts(" describe set the working-copy commit message")+ stdio.puts(" commit describe and start a new change")+ stdio.puts(" undo restore the previous operation view")+ stdio.puts(" op operation log commands")+ stdio.puts(" fsck verify repository integrity")+ stdio.puts(" self-test run the format self-tests")+ stdio.puts(" version print version information")+ stdio.puts(" bench-import compare lazy import metadata; requires git")+ stdio.puts(" help show help for a command")+ stdio.puts("")+ stdio.puts("run 'vn help <command>' for details")+}++fn show_init() void = trust {+ stdio.puts("usage: vn init [path] [-git-import:<gitdir>]")+ stdio.puts("")+ stdio.puts("create a veins repository, optionally importing an existing git repository")+ stdio.puts("")+ stdio.puts("arguments:")+ stdio.puts(" [path] directory to create (default: .)")+ stdio.puts("")+ stdio.puts("options:")+ stdio.puts(" -git-import:<gitdir> import reachable commits and refs from <gitdir>")+}++fn show_git() void = trust {+ stdio.puts("usage: vn git <subcommand> [arguments]")+ stdio.puts("")+ stdio.puts("git bridge commands:")+ stdio.puts(" import [-source:<gitdir>] [path]")+ stdio.puts(" import reachable git commits and refs")+ stdio.puts(" export [path] export commits into the git mirror")+ stdio.puts("")+ stdio.puts("run 'vn help git <subcommand>' for details")+}++fn show_git_import() void = trust {+ stdio.puts("usage: vn git import [-source:<gitdir>] [path]")+ stdio.puts("")+ stdio.puts("import commits and refs reachable from a git repository")+ stdio.puts("")+ stdio.puts("arguments:")+ stdio.puts(" [path] veins repository (default: .)")+ stdio.puts("")+ stdio.puts("options:")+ stdio.puts(" -source:<gitdir> prepare the mirror from <gitdir> before importing")+}++fn show_checkout() void = trust {+ stdio.puts("usage: vn checkout [rev]")+ stdio.puts("")+ stdio.puts("write a revision into the working directory")+ stdio.puts("")+ stdio.puts("arguments:")+ stdio.puts(" [rev] revision to check out")+}++fn show_fsck() void = trust {+ stdio.puts("usage: vn fsck [path] [-verbose]")+ stdio.puts("")+ stdio.puts("verify pack, index, object, and operation-log integrity")+ stdio.puts("")+ stdio.puts("arguments:")+ stdio.puts(" [path] repository to check (default: .)")+ stdio.puts("")+ stdio.puts("options:")+ stdio.puts(" -v, -verbose print verbose output")+}++fn show_selftest() void = trust {+ stdio.puts("usage: vn self-test")+ stdio.puts("")+ stdio.puts("run the format self-tests")+}++fn show_bench_import() void = trust {+ stdio.puts("usage: vn bench-import <gitdir>")+ stdio.puts("")+ stdio.puts("run the lazy-import metadata pass using the git CLI backend")+ stdio.puts("and print commit, tree, entry, and lazy-blob counts")+}++fn show_version() void = trust {+ stdio.puts("usage: vn version")+ stdio.puts("")+ stdio.puts("print version information")+}++fn show_status() void = trust {+ stdio.puts("usage: vn status")+ stdio.puts("")+ stdio.puts("show working-copy changes relative to the parent commit")+}++fn show_log() void = trust {+ stdio.puts("usage: vn log [-rev <revset>] [-no-col-titles]")+ stdio.puts("")+ stdio.puts("show commit history, newest first")+ stdio.puts("")+ stdio.puts("options:")+ stdio.puts(" -rev <revset> show only the given revision set")+ stdio.puts(" -no-col-titles omit column titles")+}++fn show_diff() void = trust {+ stdio.puts("usage: vn diff [-rev <rev>] [<rev> <rev>]")+ stdio.puts("")+ stdio.puts("show a unified diff")+}++fn show_new() void = trust {+ stdio.puts("usage: vn new [<rev>...]")+ stdio.puts("")+ stdio.puts("start a new empty change on top of the working copy or a revision")+}++fn show_describe() void = trust {+ stdio.puts("usage: vn describe [-message <message>] [<message>]")+ stdio.puts("")+ stdio.puts("set the working-copy commit message")+}++fn show_commit() void = trust {+ stdio.puts("usage: vn commit -message <message>")+ stdio.puts("")+ stdio.puts("set the message and start a new change")+}++fn show_undo() void = trust {+ stdio.puts("usage: vn undo")+ stdio.puts("")+ stdio.puts("record an operation that restores the previous operation view")+}++fn show_op() void = trust {+ stdio.puts("usage: vn op <log|restore|revert> [<op>]")+ stdio.puts("")+ stdio.puts("inspect and restore operations")+}++fn show_git_export() void = trust {+ stdio.puts("usage: vn git export [path]")+ stdio.puts("")+ stdio.puts("export commits reachable from bookmarks and tags into .veins/git")+}++fn show_help() void = trust {+ stdio.puts("usage: vn help [command]")+ stdio.puts("")+ stdio.puts("show help for the program or a command")+ stdio.puts("")+ stdio.puts("arguments:")+ stdio.puts(" [command] command to describe")+}++pub fn run(args: list[ref u8], start: usize) i32 = trust {+ if start >= @len(args) {+ usage()+ return 0+ }+ val cmd_opt = @get(args, start)+ val cmd: mut ref u8 = none+ match cmd_opt {+ some c => {+ cmd = c+ }+ none => {+ usage()+ return 0+ }+ }++ if cmd_is(cmd, c"init", 4) {+ show_init()+ return 0+ }+ if cmd_is(cmd, c"status", 6) {+ show_status()+ return 0+ }+ if cmd_is(cmd, c"log", 3) {+ show_log()+ return 0+ }+ if cmd_is(cmd, c"diff", 4) {+ show_diff()+ return 0+ }+ if cmd_is(cmd, c"new", 3) {+ show_new()+ return 0+ }+ if cmd_is(cmd, c"describe", 8) {+ show_describe()+ return 0+ }+ if cmd_is(cmd, c"commit", 6) {+ show_commit()+ return 0+ }+ if cmd_is(cmd, c"undo", 4) {+ show_undo()+ return 0+ }+ if cmd_is(cmd, c"op", 2) {+ show_op()+ return 0+ }+ if cmd_is(cmd, c"git", 3) {+ if start + 1 < @len(args) {+ val sub_opt = @get(args, start + 1)+ if sub_opt is some sub {+ if cmd_is(sub, c"import", 6) {+ show_git_import()+ return 0+ }+ if cmd_is(sub, c"export", 6) {+ show_git_export()+ return 0+ }+ msg.error_prefix()+ stdio.eprint("unknown git subcommand: {s}\n", {str.from_cstr(sub)})+ return 1+ }+ }+ show_git()+ return 0+ }+ if cmd_is(cmd, c"checkout", 8) {+ show_checkout()+ return 0+ }+ if cmd_is(cmd, c"fsck", 4) {+ show_fsck()+ return 0+ }+ if cmd_is(cmd, c"self-test", 9) {+ show_selftest()+ return 0+ }+ if cmd_is(cmd, c"version", 7) {+ show_version()+ return 0+ }+ if cmd_is(cmd, c"bench-import", 12) {+ show_bench_import()+ return 0+ }+ if cmd_is(cmd, c"help", 4) {+ show_help()+ return 0+ }++ msg.error_prefix()+ stdio.eprint("unknown command: {s}\n", {str.from_cstr(cmd)})+ usage()+ return 1+}--- /dev/null+++ b/veins/src/cli/init_cmd.sx@@ -0,0 +1,38 @@+/// `vn init`: create the on-disk repository skeleton and optionally import git.++val str = use("std/string")+val stdio = use("std/stdio")+val msg = use("../core/msg.sx")+val layout = use("../store/layout.sx")+val mirror = use("../git/mirror.sx")+val import = use("../git/import.sx")++pub fn run(path: str.StringView, source: option[str.StringView]) i32 = trust {+ val result = layout.init(path)+ match result {+ ok repo => {+ msg.info_prefix()+ stdio.print("initialized veins repository at {s}\n", {layout.root_view(repo)})+ val mut_source = source+ if mut_source is some src {+ val prepared: i32 = mirror.prepare(repo, src)+ if prepared != 0 {+ msg.error_prefix()+ stdio.eprint("cannot prepare git mirror (code {d})\n", {prepared})+ layout.free_repo(repo)+ return 1+ }+ val status: i32 = import.run(repo)+ layout.free_repo(repo)+ return status+ }+ layout.free_repo(repo)+ return 0+ }+ err code => {+ msg.error_prefix()+ stdio.eprint("init failed with code {d}\n", {code})+ return 1+ }+ }+}--- /dev/null+++ b/veins/src/cli/log_cmd.sx@@ -0,0 +1,372 @@+/// `vn log [-rev <revset>]`: show commit history, newest first.++val str = use("std/string")+val stdio = use("std/stdio")+val msg = use("../core/msg.sx")+val terminal = use("std/terminal")+val bytes = use("../core/bytes.sx")+val lists = use("../core/lists.sx")+val objid = use("../object/id.sx")+val view = use("../object/view.sx")+val graph = use("../object/graph.sx")+val changeid = use("../object/changeid.sx")+val treewalk = use("../object/treewalk.sx")+val datetime = use("../core/datetime.sx")+val store = use("../store/store.sx")+val state = use("../store/state.sx")+val layout = use("../store/layout.sx")+val viewops = use("../store/viewops.sx")+val snapshot = use("../worktree/snapshot.sx")++type LogRec = {+ id: mut objid.Id+ cid: mut bytes.Bytes+ seconds: mut i64+ tree: mut objid.Id+ message: mut bytes.Bytes+ author: mut bytes.Bytes+ conflicted: mut bool+ has_changes: mut bool+}++fn new_rec(+ id: objid.Id,+ cid: bytes.Bytes,+ seconds: i64,+ tree_id: objid.Id,+ message: bytes.Bytes,+ author: bytes.Bytes+) ref LogRec = trust {+ val r: mut ref LogRec = @alloc(@sizeof(LogRec)) as ref LogRec+ r.id = graph.copy_id(id)+ r.cid = bytes.Bytes.dup(cid)+ r.seconds = seconds+ r.tree = graph.copy_id(tree_id)+ r.message = bytes.Bytes.dup(message)+ r.author = bytes.Bytes.dup(author)+ r.conflicted = false+ r.has_changes = false+ return r+}++fn free_recs(rs: list[ref LogRec]) void = trust {+ for r in rs {+ if r.id.ptr != none {+ val p: mut ref void = r.id.ptr as ref void+ @free(p)+ }+ if r.cid.ptr != none {+ val p2: mut ref void = r.cid.ptr as ref void+ @free(p2)+ }+ if r.tree.ptr != none {+ val p3: mut ref void = r.tree.ptr as ref void+ @free(p3)+ }+ if r.message.ptr != none {+ val p4: mut ref void = r.message.ptr as ref void+ @free(p4)+ }+ if r.author.ptr != none {+ val p5: mut ref void = r.author.ptr as ref void+ @free(p5)+ }+ val rp: mut ref void = r as ref void+ @free(rp)+ }+ @listfree(rs)+}++fn rec_at(rs: list[ref LogRec], i: usize) ref LogRec = trust {+ val o = @get(rs, i)+ if o is some r {+ return r+ }+ assert false+ return none+}++fn sort_recs(rs: mut list[ref LogRec]) void = trust {+ val i: mut usize = 1+ for i < @len(rs) {+ val cur = @get(rs, i)+ val c: mut ref LogRec = none+ if cur is some v {+ c = v+ }+ val j: mut usize = i+ for j > 0 {+ val prev_opt = @get(rs, j - 1)+ val prev: mut ref LogRec = none+ if prev_opt is some v2 {+ prev = v2+ }+ if prev.seconds >= c.seconds {+ break+ }+ @set(rs, j, prev)+ j--+ }+ @set(rs, j, c)+ i+++ }+}++fn first_line(msg: bytes.Bytes) bytes.Bytes = trust {+ val i: mut usize = 0+ for i < msg.len {+ if bytes.Bytes.at(msg, i) == 10 {+ return bytes.Bytes.slice(msg, 0, i)+ }+ i+++ }+ return msg+}++fn print_cell(+ text: str.StringView,+ width: usize,+ color: terminal.Color,+ dim: bool+) void = trust {+ if dim {+ terminal.print_styled(text, color, terminal.Color.Default, terminal.Style.Dim)+ } elif color == terminal.Color.Default {+ stdio.print("{s}", {text})+ } else {+ terminal.print(text, color)+ }+ val pad: mut i64 = width as i64 - text.len+ for pad > 0 {+ stdio.print(" ", {})+ pad--+ }+}++fn print_gap() void = trust {+ stdio.print(" ", {})+}++fn short_cid(rs: list[ref LogRec], idx: usize) bytes.Bytes = trust {+ val target: ref LogRec = rec_at(rs, idx)+ val limit: usize = target.cid.len+ val len: mut usize = 4+ if len > limit {+ len = limit+ }+ for len < limit {+ val prefix: bytes.Bytes = bytes.Bytes.slice(target.cid, 0, len)+ val unique: mut bool = true+ val j: mut usize = 0+ for j < @len(rs) {+ if j != idx {+ val other: ref LogRec = rec_at(rs, j)+ if !bytes.Bytes.eql(other.cid, target.cid) {+ if bytes.Bytes.starts_with(other.cid, prefix) {+ unique = false+ break+ }+ }+ }+ j+++ }+ if unique {+ break+ }+ len+++ }+ return bytes.Bytes.dup(bytes.Bytes.slice(target.cid, 0, len))+}++pub fn run(repo: layout.Repo, rev: bytes.Bytes, col_titles: bool) i32 = trust {+ val snap: i32 = snapshot.run(repo)+ if snap != 0 {+ return snap+ }+ val st: store.Store = store.open_all(repo)+ val v_opt = state.current_view(repo, st.handles)+ val v: mut ref view.View = none+ match v_opt {+ some x => {+ v = x+ }+ none => {+ store.close(st)+ msg.error_prefix()+ stdio.eprint("no operation state\n", {})+ return 1+ }+ }+ val wc_opt = viewops.working_copy(v)+ val wc: mut objid.Id = objid.id_none()+ if wc_opt is some id {+ wc = id+ }+ val roots: list[objid.Id] = graph.roots(v)+ val ids: list[objid.Id] = collect_ids(st.handles, v, roots, rev)+ graph.free_ids(roots)+ val recs: mut list[ref LogRec] = lists.new[ref LogRec]()+ for id in ids {+ val lc_opt = graph.load_commit(st.handles, id)+ if lc_opt is some lc {+ val cid_full: bytes.Bytes = changeid.encode(lc.c.change_id)+ val msg: bytes.Bytes = first_line(lc.c.message)+ val rec: mut ref LogRec = new_rec(+ id,+ cid_full,+ lc.c.committer.seconds,+ lc.c.root_tree,+ msg,+ lc.c.author.name+ )+ rec.conflicted = treewalk.conflicted(st.handles, lc.c.root_tree)+ if objid.Id.eql(id, wc) {+ rec.has_changes = graph.has_changes(st.handles, lc)+ }+ changeid.free(cid_full)+ graph.free_loaded(lc)+ @append(recs, rec)+ }+ }+ sort_recs(recs)+ val w_commit: usize = 12+ val w_change: mut usize = 6+ val w_date: usize = 19+ val w_author: mut usize = 6+ val k: mut usize = 0+ for k < @len(recs) {+ val r: ref LogRec = rec_at(recs, k)+ val cid: bytes.Bytes = short_cid(recs, k)+ if cid.len > w_change {+ w_change = cid.len+ }+ changeid.free(cid)+ if r.author.len > w_author {+ w_author = r.author.len+ }+ k+++ }+ if col_titles {+ print_cell(str.from_cstr(c""), 1, terminal.Color.Default, false)+ stdio.print(" ", {})+ print_cell(str.from_cstr(c"Commit"), w_commit, terminal.Color.Default, false)+ print_gap()+ print_cell(str.from_cstr(c"Change"), w_change, terminal.Color.Default, false)+ print_gap()+ print_cell(str.from_cstr(c"Date"), w_date, terminal.Color.Default, false)+ print_gap()+ print_cell(str.from_cstr(c"Author"), w_author, terminal.Color.Default, false)+ print_gap()+ stdio.print("Message\n", {})+ }+ val i: mut usize = 0+ for i < @len(recs) {+ val r: ref LogRec = rec_at(recs, i)+ val marker: mut str.StringView = str.from_cstr(c" ")+ val marker_color: mut terminal.Color = terminal.Color.Default+ if objid.Id.eql(r.id, wc) {+ marker = str.from_cstr(c"@")+ marker_color = terminal.Color.Red+ if r.has_changes {+ marker_color = terminal.Color.BrightCyan+ }+ }+ val hex: ref u8 = objid.Id.hex(r.id)+ val short: str.StringView = str.view(hex, 12)+ val cid: bytes.Bytes = short_cid(recs, i)+ val stamp: bytes.Bytes = datetime.format_utc(r.seconds)+ val msg_view = str.view(r.message.ptr, r.message.len as i64)+ val author_view = str.view(r.author.ptr, r.author.len as i64)+ print_cell(marker, 1, marker_color, false)+ stdio.print(" ", {})+ print_cell(short, w_commit, terminal.Color.Red, false)+ print_gap()+ print_cell(+ str.view(cid.ptr, cid.len as i64),+ w_change,+ terminal.Color.Red,+ false+ )+ print_gap()+ print_cell(+ str.view(stamp.ptr, stamp.len as i64),+ w_date,+ terminal.Color.Cyan,+ true+ )+ print_gap()+ print_cell(author_view, w_author, terminal.Color.Cyan, false)+ print_gap()+ if msg_view.len > 0 {+ terminal.print(msg_view, terminal.Color.Green)+ } else {+ terminal.print(str.from_cstr(c"<unset>"), terminal.Color.BrightBlack)+ }+ val names = viewops.bookmark_names(v, r.id)+ for name in names {+ stdio.print(" [{s}]", {str.view(name.ptr, name.len as i64)})+ }+ @listfree(names)+ val tnames = viewops.tag_names(v, r.id)+ for name in tnames {+ stdio.print(" <{s}>", {str.view(name.ptr, name.len as i64)})+ }+ @listfree(tnames)+ if r.conflicted {+ stdio.print(" (conflicted)", {})+ }+ val divergent: mut bool = false+ val j: mut usize = 0+ for j < @len(recs) {+ if j != i {+ val other = rec_at(recs, j)+ if bytes.Bytes.eql(other.cid, r.cid) {+ divergent = true+ break+ }+ }+ j+++ }+ if divergent {+ stdio.print(" (divergent)", {})+ }+ stdio.print("\n", {})+ @free(hex as ref void)+ changeid.free(cid)+ // timestamp is freed by the arena-style process exit+ i+++ }+ free_recs(recs)+ graph.free_ids(ids)+ view.free_view(v)+ if wc.ptr != none {+ val wp: mut ref void = wc.ptr as ref void+ @free(wp)+ }+ store.close(st)+ return 0+}++fn collect_ids(+ handles: list[ref store.Handle],+ v: ref view.View,+ roots: list[objid.Id],+ rev: bytes.Bytes+) list[objid.Id] = trust {+ if rev.len == 0 || bytes.Bytes.eql(rev, bytes.bytes(c"all()", 5)) {+ return graph.collect(handles, roots)+ }+ val resolved = graph.resolve(handles, v, rev)+ match resolved {+ some id => {+ val one: mut list[objid.Id] = lists.new[objid.Id]()+ @append(one, graph.copy_id(id))+ val out = graph.collect(handles, one)+ graph.free_ids(one)+ return out+ }+ none => {+ return lists.new[objid.Id]()+ }+ }+}--- /dev/null+++ b/veins/src/cli/new_cmd.sx@@ -0,0 +1,379 @@+/// `vn describe`, `vn new`, and `vn commit`.++val stdio = use("std/stdio")+val msg = use("../core/msg.sx")+val bytes = use("../core/bytes.sx")+val buf = use("../core/buf.sx")+val lists = use("../core/lists.sx")+val prim = use("../core/primitives.sx")+val random = use("std/crypto/random")+val objid = use("../object/id.sx")+val types = use("../object/types.sx")+val commit = use("../object/commit.sx")+val graph = use("../object/graph.sx")+val store = use("../store/store.sx")+val layout = use("../store/layout.sx")+val txn = use("../store/txn.sx")+val viewops = use("../store/viewops.sx")+val identity = use("../core/identity.sx")+val gitmap = use("../git/map.sx")+val snapshot = use("../worktree/snapshot.sx")+val checkout = use("../worktree/checkout.sx")++val NOTHING_TO_COMMIT: i32 = 2++fn copy_id(id: objid.Id) objid.Id = trust {+ val out: ref u8 = @alloc(32) as ref u8+ @memcpy(out as ref void, id.ptr as ref void, 32)+ return objid.id(out)+}++fn copy_renames(rs: list[ref commit.Rename]) list[ref commit.Rename] = trust {+ val out: mut list[ref commit.Rename] = lists.new[ref commit.Rename]()+ for r in rs {+ @append(+ out,+ commit.new_rename(+ r.parent_index,+ r.kind,+ bytes.Bytes.dup(r.from_path),+ bytes.Bytes.dup(r.to_path)+ )+ )+ }+ return out+}++fn copy_kvs(xs: list[ref prim.KeyValue]) list[ref prim.KeyValue] = trust {+ val out: mut list[ref prim.KeyValue] = lists.new[ref prim.KeyValue]()+ for kv in xs {+ @append(out, commit.new_kv(bytes.Bytes.dup(kv.key), bytes.Bytes.dup(kv.value)))+ }+ return out+}++fn free_renames(rs: list[ref commit.Rename]) void = trust {+ for r in rs {+ if r.from_path.ptr != none {+ val fp: mut ref void = r.from_path.ptr as ref void+ @free(fp)+ }+ if r.to_path.ptr != none {+ val tp: mut ref void = r.to_path.ptr as ref void+ @free(tp)+ }+ val rp: mut ref void = r as ref void+ @free(rp)+ }+ @listfree(rs)+}++fn free_kvs(xs: list[ref prim.KeyValue]) void = trust {+ for kv in xs {+ if kv.key.ptr != none {+ val kp: mut ref void = kv.key.ptr as ref void+ @free(kp)+ }+ if kv.value.ptr != none {+ val vp: mut ref void = kv.value.ptr as ref void+ @free(vp)+ }+ val xp: mut ref void = kv as ref void+ @free(xp)+ }+ @listfree(xs)+}++fn join_args(args: list[bytes.Bytes]) bytes.Bytes = trust {+ val b: mut buf.Buf = buf.new(64)+ val i: mut usize = 0+ for i < @len(args) {+ if i > 0 {+ buf.Buf.put_u8(b, 32)+ }+ val o = @get(args, i)+ if o is some v {+ buf.Buf.put_bytes(b, v)+ }+ i+++ }+ val out: bytes.Bytes = bytes.Bytes.dup(buf.Buf.view(b))+ buf.Buf.free(b)+ return out+}++fn describe_impl(repo: layout.Repo, args: list[bytes.Bytes], require_changes: bool) i32 = trust {+ val snap: i32 = snapshot.run(repo)+ if snap != 0 {+ return snap+ }+ val message: bytes.Bytes = join_args(args)+ val tx_opt = txn.begin(repo)+ val tx: mut ref txn.Txn = none+ match tx_opt {+ some t => {+ tx = t+ }+ none => {+ msg.error_prefix()+ stdio.eprint("cannot load repository state\n", {})+ val mp: mut ref void = message.ptr as ref void+ @free(mp)+ return 1+ }+ }+ val wc_opt = viewops.working_copy(tx.view)+ val wc: mut objid.Id = objid.id_none()+ val have_wc: mut bool = false+ if wc_opt is some id {+ wc = id+ have_wc = true+ }+ if !have_wc {+ msg.error_prefix()+ stdio.eprint("no working-copy commit\n", {})+ txn.abort(tx)+ val mp2: mut ref void = message.ptr as ref void+ @free(mp2)+ return 1+ }+ val st: store.Store = store.open_all(repo)+ val lc_opt = graph.load_commit(st.handles, wc)+ if lc_opt is none {+ msg.error_prefix()+ stdio.eprint("cannot read working-copy commit\n", {})+ store.close(st)+ txn.abort(tx)+ val mp2: mut ref void = message.ptr as ref void+ @free(mp2)+ return 1+ }+ val lc: mut ref graph.LoadedCommit = none+ if lc_opt is some x {+ lc = x+ }+ val changed: bool = graph.has_changes(st.handles, lc)+ val same_message: bool = bytes.Bytes.eql(message, lc.c.message)+ if !changed && (require_changes || same_message) {+ if require_changes {+ msg.info_prefix()+ stdio.print("nothing to commit, working copy clean\n", {})+ }+ store.close(st)+ txn.abort(tx)+ graph.free_loaded(lc)+ val mp: mut ref void = message.ptr as ref void+ @free(mp)+ if wc.ptr != none {+ val wp: mut ref void = wc.ptr as ref void+ @free(wp)+ }+ if require_changes {+ return NOTHING_TO_COMMIT+ }+ return 0+ }+ val sig = identity.signature(repo)+ val parents: mut list[objid.Id] = lists.new[objid.Id]()+ for p in lc.c.parents {+ @append(parents, copy_id(p))+ }+ val renames: list[ref commit.Rename] = copy_renames(lc.c.renames)+ val extra: list[ref prim.KeyValue] = copy_kvs(lc.c.extra)+ val nc: mut ref commit.Commit = @alloc(@sizeof(commit.Commit)) as ref commit.Commit+ nc.version = 1+ nc.parents = parents+ nc.root_tree = copy_id(lc.c.root_tree)+ nc.change_id = lc.c.change_id+ nc.author = lc.c.author+ nc.committer = sig+ nc.message = message+ nc.renames_state = lc.c.renames_state+ nc.renames = renames+ nc.extra = extra+ val encoded: bytes.Bytes = commit.encode(nc)+ val new_id: objid.Id = txn.add_object(tx, types.COMMIT, encoded)+ viewops.remove_head(tx.view, wc)+ viewops.set_workspace(tx.view, new_id)+ viewops.rebuild_heads(tx.view)+ val status: i32 = txn.finish(tx, bytes.bytes(c"describe", 8))+ if status == 0 {+ val _ = gitmap.mark_native(repo, new_id)+ }+ store.close(st)+ graph.free_loaded(lc)+ @listfree(parents)+ free_renames(renames)+ free_kvs(extra)+ @free(nc.root_tree.ptr as ref void)+ @free(nc as ref void)+ val mp3: mut ref void = message.ptr as ref void+ @free(mp3)+ val nip: mut ref void = new_id.ptr as ref void+ @free(nip)+ if wc.ptr != none {+ val wp: mut ref void = wc.ptr as ref void+ @free(wp)+ }+ identity.free_sig(sig)+ return status+}++pub fn describe(repo: layout.Repo, args: list[bytes.Bytes]) i32 = trust {+ return describe_impl(repo, args, false)+}++pub fn commit_changes(repo: layout.Repo, args: list[bytes.Bytes]) i32 = trust {+ val d: i32 = describe_impl(repo, args, true)+ if d == NOTHING_TO_COMMIT {+ return 0+ }+ if d != 0 {+ return d+ }+ val empty: list[bytes.Bytes] = lists.new[bytes.Bytes]()+ val status: i32 = new_change(repo, empty)+ @listfree(empty)+ return status+}++pub fn new_change(repo: layout.Repo, revs: list[bytes.Bytes]) i32 = trust {+ val snap: i32 = snapshot.run(repo)+ if snap != 0 {+ return snap+ }+ val tx_opt = txn.begin(repo)+ val tx: mut ref txn.Txn = none+ match tx_opt {+ some t => {+ tx = t+ }+ none => {+ msg.error_prefix()+ stdio.eprint("cannot load repository state\n", {})+ return 1+ }+ }+ val st: store.Store = store.open_all(repo)+ val wc_opt = viewops.working_copy(tx.view)+ val wc: mut objid.Id = objid.id_none()+ val have_wc: mut bool = false+ if wc_opt is some id {+ wc = id+ have_wc = true+ }+ val parents: mut list[objid.Id] = lists.new[objid.Id]()+ val root_tree: mut objid.Id = objid.id_none()+ if @len(revs) == 0 {+ if !have_wc {+ msg.error_prefix()+ stdio.eprint("no working-copy commit\n", {})+ store.close(st)+ txn.abort(tx)+ return 1+ }+ val lc_opt = graph.load_commit(st.handles, wc)+ match lc_opt {+ some lc => {+ @append(parents, copy_id(wc))+ root_tree = copy_id(lc.c.root_tree)+ graph.free_loaded(lc)+ }+ none => {+ msg.error_prefix()+ stdio.eprint("cannot read working-copy commit\n", {})+ store.close(st)+ txn.abort(tx)+ return 1+ }+ }+ } else {+ val i: mut usize = 0+ val mut_failed: mut bool = false+ for i < @len(revs) {+ val r = @get(revs, i)+ val rev: mut bytes.Bytes = bytes.empty()+ if r is some v {+ rev = v+ }+ val resolved = graph.resolve(st.handles, tx.view, rev)+ match resolved {+ some id => {+ @append(parents, copy_id(id))+ if i == 0 {+ val lc_opt = graph.load_commit(st.handles, id)+ match lc_opt {+ some lc => {+ root_tree = copy_id(lc.c.root_tree)+ graph.free_loaded(lc)+ }+ none => {+ mut_failed = true+ }+ }+ }+ }+ none => {+ mut_failed = true+ }+ }+ i+++ }+ if mut_failed {+ msg.error_prefix()+ stdio.eprint("unknown revision\n", {})+ store.close(st)+ txn.abort(tx)+ graph.free_ids(parents)+ return 1+ }+ }+ val cid: ref u8 = @alloc(16) as ref u8+ random.random_bytes(cid as ref void, 16)+ val sig = identity.signature(repo)+ val renames: list[ref commit.Rename] = lists.new[ref commit.Rename]()+ val extra: list[ref prim.KeyValue] = lists.new[ref prim.KeyValue]()+ val nc: mut ref commit.Commit = @alloc(@sizeof(commit.Commit)) as ref commit.Commit+ nc.version = 1+ nc.parents = parents+ nc.root_tree = root_tree+ nc.change_id = objid.change_id(cid)+ nc.author = sig+ nc.committer = sig+ nc.message = bytes.empty()+ nc.renames_state = commit.RENAMES_RECORDED+ nc.renames = renames+ nc.extra = extra+ val encoded: bytes.Bytes = commit.encode(nc)+ val new_id: objid.Id = txn.add_object(tx, types.COMMIT, encoded)+ if have_wc {+ viewops.remove_head(tx.view, wc)+ }+ viewops.set_workspace(tx.view, new_id)+ viewops.rebuild_heads(tx.view)+ val status: i32 = txn.finish(tx, bytes.bytes(c"new", 3))+ if status == 0 {+ val _ = gitmap.mark_native(repo, new_id)+ }+ store.close(st)+ @listfree(parents)+ @listfree(renames)+ @listfree(extra)+ @free(root_tree.ptr as ref void)+ @free(nc as ref void)+ @free(cid as ref void)+ val nip: mut ref void = new_id.ptr as ref void+ @free(nip)+ if wc.ptr != none {+ val wp: mut ref void = wc.ptr as ref void+ @free(wp)+ }+ identity.free_sig(sig)+ if status != 0 {+ return status+ }+ if @len(revs) > 0 {+ return checkout.run(repo, bytes.empty())+ }+ return 0+}--- /dev/null+++ b/veins/src/cli/op_cmd.sx@@ -0,0 +1,330 @@+/// Operation log commands: `op log`, `op restore`, `op revert`, and `undo`.++val str = use("std/string")+val stdio = use("std/stdio")+val msg = use("../core/msg.sx")+val bytes = use("../core/bytes.sx")+val lists = use("../core/lists.sx")+val objid = use("../object/id.sx")+val operation = use("../object/operation.sx")+val view = use("../object/view.sx")+val datetime = use("../core/datetime.sx")+val store = use("../store/store.sx")+val state = use("../store/state.sx")+val layout = use("../store/layout.sx")+val txn = use("../store/txn.sx")++type OpRec = {+ id: mut objid.Id+ op: mut ref operation.Operation+}++fn copy_id(id: objid.Id) objid.Id = trust {+ val out: ref u8 = @alloc(32) as ref u8+ @memcpy(out as ref void, id.ptr as ref void, 32)+ return objid.id(out)+}++fn contains(ids: list[objid.Id], id: objid.Id) bool = trust {+ for x in ids {+ if objid.Id.eql(x, id) {+ return true+ }+ }+ return false+}++fn free_ids(ids: list[objid.Id]) void = trust {+ for id in ids {+ if id.ptr != none {+ val p: mut ref void = id.ptr as ref void+ @free(p)+ }+ }+ @listfree(ids)+}++fn collect(+ handles: list[ref store.Handle],+ heads: list[objid.Id]+) list[ref OpRec] = trust {+ val out: mut list[ref OpRec] = lists.new[ref OpRec]()+ val seen: mut list[objid.Id] = lists.new[objid.Id]()+ val stack: mut list[objid.Id] = lists.new[objid.Id]()+ for h in heads {+ @append(stack, copy_id(h))+ }+ for @len(stack) > 0 {+ val id: objid.Id = @remove(stack, @len(stack) - 1)+ if contains(seen, id) {+ val ip: mut ref void = id.ptr as ref void+ @free(ip)+ continue+ }+ @append(seen, copy_id(id))+ val op_opt = state.read_operation(handles, id)+ if op_opt is some op {+ for p in op.parents {+ if !contains(seen, p) {+ @append(stack, copy_id(p))+ }+ }+ val rec: mut ref OpRec = @alloc(@sizeof(OpRec)) as ref OpRec+ rec.id = id+ rec.op = op+ @append(out, rec)+ }+ }+ @listfree(stack)+ free_ids(seen)+ return out+}++fn free_recs(recs: list[ref OpRec]) void = trust {+ for r in recs {+ operation.free_operation(r.op)+ if r.id.ptr != none {+ val p: mut ref void = r.id.ptr as ref void+ @free(p)+ }+ val rp: mut ref void = r as ref void+ @free(rp)+ }+ @listfree(recs)+}++fn rec_at(rs: list[ref OpRec], i: usize) ref OpRec = trust {+ val o = @get(rs, i)+ if o is some r {+ return r+ }+ assert false+ return none+}++fn sort_recs(rs: mut list[ref OpRec]) void = trust {+ val i: mut usize = 1+ for i < @len(rs) {+ val cur = @get(rs, i)+ val c: mut ref OpRec = none+ if cur is some v {+ c = v+ }+ val j: mut usize = i+ for j > 0 {+ val prev_o = @get(rs, j - 1)+ val prev: mut ref OpRec = none+ if prev_o is some vv {+ prev = vv+ }+ if prev.op.end.ms >= c.op.end.ms {+ break+ }+ @set(rs, j, prev)+ j--+ }+ @set(rs, j, c)+ i+++ }+}++fn resolve_op(recs: list[ref OpRec], text: bytes.Bytes) option[objid.Id] = trust {+ val matches: mut list[objid.Id] = lists.new[objid.Id]()+ val i: mut usize = 0+ for i < @len(recs) {+ val r = rec_at(recs, i)+ val hex: ref u8 = objid.Id.hex(r.id)+ val full: bytes.Bytes = bytes.bytes(hex, 64)+ val matched: bool = full.len >= text.len && bytes.Bytes.eql(+ bytes.Bytes.slice(full, 0, text.len),+ text+ )+ @free(hex as ref void)+ if matched {+ @append(matches, copy_id(r.id))+ }+ i+++ }+ val out: mut option[objid.Id] = none+ if @len(matches) == 1 {+ val o = @get(matches, 0)+ if o is some only {+ out = some copy_id(only)+ }+ }+ free_ids(matches)+ return out+}++fn find_rec(recs: list[ref OpRec], id: objid.Id) option[ref OpRec] = trust {+ for r in recs {+ if objid.Id.eql(r.id, id) {+ return some r+ }+ }+ return none+}++pub fn log(repo: layout.Repo) i32 = trust {+ val st: store.Store = store.open_all(repo)+ val heads: list[objid.Id] = state.heads(repo)+ val recs: mut list[ref OpRec] = collect(st.handles, heads)+ sort_recs(recs)+ val i: mut usize = 0+ for i < @len(recs) {+ val r = rec_at(recs, i)+ val hex: ref u8 = objid.Id.hex(r.id)+ val stamp: bytes.Bytes = datetime.format_utc(r.op.end.ms / 1000)+ val marker: mut str.StringView = str.from_cstr(c" ")+ if contains(heads, r.id) {+ marker = str.from_cstr(c"@")+ }+ stdio.print(+ "{s} {s} {s} {s}\n",+ {+ marker,+ str.view(hex, 12),+ str.view(stamp.ptr, stamp.len as i64),+ str.view(r.op.description.ptr, r.op.description.len as i64)+ }+ )+ @free(hex as ref void)+ // timestamp is freed by the arena-style process exit+ i+++ }+ free_recs(recs)+ free_ids(heads)+ store.close(st)+ return 0+}++fn write_view(+ repo: layout.Repo,+ new_view: ref view.View,+ description: bytes.Bytes+) i32 = trust {+ val tx_opt = txn.begin(repo)+ val tx: mut ref txn.Txn = none+ match tx_opt {+ some t => {+ tx = t+ }+ none => {+ msg.error_prefix()+ stdio.eprint("cannot load repository state\n", {})+ return 1+ }+ }+ view.free_view(tx.view)+ tx.view = new_view+ val status: i32 = txn.finish(tx, description)+ return status+}++pub fn restore(repo: layout.Repo, text: bytes.Bytes) i32 = trust {+ val st: store.Store = store.open_all(repo)+ val heads: list[objid.Id] = state.heads(repo)+ val recs: mut list[ref OpRec] = collect(st.handles, heads)+ val target = resolve_op(recs, text)+ val status: mut i32 = 1+ if target is some tid {+ val rec_opt = find_rec(recs, tid)+ if rec_opt is some rec {+ val target_view = state.read_view(st.handles, rec.op.view)+ if target_view is some tv {+ status = write_view(repo, tv, bytes.bytes(c"op restore", 10))+ } else {+ msg.error_prefix()+ stdio.eprint("cannot read operation view\n", {})+ }+ }+ } else {+ msg.error_prefix()+ stdio.eprint("unknown operation\n", {})+ }+ free_recs(recs)+ free_ids(heads)+ store.close(st)+ return status+}++pub fn revert(repo: layout.Repo, text: bytes.Bytes) i32 = trust {+ // A revert of the latest operation restores its parent view. More complex+ // three-way inverses are handled by the merge engine in a later milestone.+ val st: store.Store = store.open_all(repo)+ val heads: list[objid.Id] = state.heads(repo)+ val recs: mut list[ref OpRec] = collect(st.handles, heads)+ val target = resolve_op(recs, text)+ val status: mut i32 = 1+ if target is some tid {+ val rec_opt = find_rec(recs, tid)+ if rec_opt is some rec {+ if @len(rec.op.parents) > 0 {+ val p = @get(rec.op.parents, 0)+ if p is some pid {+ val parent_opt = state.read_operation(st.handles, pid)+ if parent_opt is some parent {+ val pv = state.read_view(st.handles, parent.view)+ if pv is some tv {+ status = write_view(repo, tv, bytes.bytes(c"op revert", 9))+ }+ operation.free_operation(parent)+ }+ }+ } else {+ val empty: ref view.View = state.empty_view()+ status = write_view(repo, empty, bytes.bytes(c"op revert", 9))+ }+ }+ } else {+ msg.error_prefix()+ stdio.eprint("unknown operation\n", {})+ }+ free_recs(recs)+ free_ids(heads)+ store.close(st)+ return status+}++pub fn undo(repo: layout.Repo) i32 = trust {+ val st: store.Store = store.open_all(repo)+ val heads: list[objid.Id] = state.heads(repo)+ if @len(heads) == 0 {+ msg.error_prefix()+ stdio.eprint("no operations to undo\n", {})+ store.close(st)+ return 1+ }+ val recs: mut list[ref OpRec] = collect(st.handles, heads)+ sort_recs(recs)+ val status: mut i32 = 1+ if @len(recs) > 0 {+ val latest = rec_at(recs, 0)+ val target_view: mut option[ref view.View] = none+ if @len(latest.op.parents) > 0 {+ val p = @get(latest.op.parents, 0)+ if p is some pid {+ val parent_opt = state.read_operation(st.handles, pid)+ if parent_opt is some parent {+ target_view = state.read_view(st.handles, parent.view)+ operation.free_operation(parent)+ }+ }+ } else {+ target_view = some(state.empty_view())+ }+ match target_view {+ some tv => {+ status = write_view(repo, tv, bytes.bytes(c"undo", 4))+ }+ none => {+ msg.error_prefix()+ stdio.eprint("cannot resolve undo target\n", {})+ }+ }+ }+ free_recs(recs)+ free_ids(heads)+ store.close(st)+ return status+}--- /dev/null+++ b/veins/src/cli/selftest_cmd.sx@@ -0,0 +1,553 @@+/// 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 msg = use("../core/msg.sx")+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+++ }+}++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+++ }+ fuzz_once(bytes.bytes(data, n))+ i+++ }+ @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"56504b310100000001000000000000008be3caa39b307b2b4a46533174cc7faa49c0ff34317302d188276c9641be35fb030001010072c385a83448a5e16853735a79a212f0377d0e40be777d121271758525dbc911"+ )+ assert_bytes_hash(+ out.index,+ c"d5dfb7b2ce4235f87856c12ff2e0b65d817dc29dfedad62ba34e71d74dca0cfc"+ )+ 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"c83c67617ae4445631508cc4edba83ba58d9e996cea40c980ec69a8b6da86458")+ val c1 = objid.object_id(types.CHUNK, bytes.Bytes.slice(bytes.bytes(data, n), 262144, n))+ assert_id(c1, c"0c91665d423fd704baae9454d24697460c4898fbf16cc6ad498d3f750d073a4b")+ val built: ref blob.BlobBuild = blob.build(data, n)+ val root = objid.object_id(types.BLOB, built.root_body)+ assert_id(root, c"937fe1a8d674aa28cb9fa074a76ea84cdc1d6c61e209f47bbdebbe4361b698cf")+ assert_id(+ blob.root_id(built),+ c"937fe1a8d674aa28cb9fa074a76ea84cdc1d6c61e209f47bbdebbe4361b698cf"+ )+ 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+++ }+ 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"8be3caa39b307b2b4a46533174cc7faa49c0ff34317302d188276c9641be35fb")+ val commit_id: objid.Id = make_commit(repo, tree_id)+ assert_id(commit_id, c"7f648b3621402df01985d121888c89c37107274fb8bb54661f12deca6cc72299")+ val conflict_id: objid.Id = make_conflict(repo)+ assert_id(conflict_id, c"02b5ddd6d982a32aa19d1c1b11d09165b44667b0c33acd993c44457dedcabd06")+ val view_id: objid.Id = make_view(repo, commit_id)+ assert_id(view_id, c"a2e19569bb3b5c28775bc8503c45c4edce6d51f55303e39bc02eec529324cd11")+ val op_id: objid.Id = make_operation(repo, view_id)+ assert_id(op_id, c"0a5494529353fb5886870a128139e07d95f40afcd831afc423617808f31dc426")+ 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/veins-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 => {+ msg.error_prefix()+ stdio.eprint("self-test: 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 {+ msg.error_prefix()+ stdio.eprint("self-test: fsck failed\n", {})+ return 1+ }+ msg.info_prefix()+ stdio.print("self-test: OK\n", {})+ return 0+}--- /dev/null+++ b/veins/src/cli/status_cmd.sx@@ -0,0 +1,124 @@+/// `vn status`: show working-copy changes relative to the parent commit.++val stdio = use("std/stdio")+val msg = use("../core/msg.sx")+val str = use("std/string")+val objid = use("../object/id.sx")+val tree = use("../object/tree.sx")+val graph = use("../object/graph.sx")+val treediff = use("../object/treediff.sx")+val treewalk = use("../object/treewalk.sx")+val view = use("../object/view.sx")+val store = use("../store/store.sx")+val state = use("../store/state.sx")+val layout = use("../store/layout.sx")+val viewops = use("../store/viewops.sx")+val snapshot = use("../worktree/snapshot.sx")++fn first_parent_tree(handles: list[ref store.Handle], id: objid.Id) option[objid.Id] = trust {+ val lc_opt = graph.load_commit(handles, id)+ val out: mut option[objid.Id] = none+ if lc_opt is some lc {+ if @len(lc.c.parents) > 0 {+ val p = @get(lc.c.parents, 0)+ if p is some pid {+ val pl = graph.load_commit(handles, pid)+ if pl is some parent {+ out = some(graph.copy_id(parent.c.root_tree))+ graph.free_loaded(parent)+ }+ }+ }+ graph.free_loaded(lc)+ }+ return out+}++fn working_tree(handles: list[ref store.Handle], id: objid.Id) option[objid.Id] = trust {+ val lc_opt = graph.load_commit(handles, id)+ val out: mut option[objid.Id] = none+ if lc_opt is some lc {+ out = some(graph.copy_id(lc.c.root_tree))+ graph.free_loaded(lc)+ }+ return out+}++pub fn run(repo: layout.Repo) i32 = trust {+ val snap: i32 = snapshot.run(repo)+ if snap != 0 {+ return snap+ }+ val st: store.Store = store.open_all(repo)+ val v_opt = state.current_view(repo, st.handles)+ val v: mut ref view = none+ match v_opt {+ some x => {+ v = x+ }+ none => {+ store.close(st)+ msg.error_prefix()+ stdio.eprint("no operation state\n", {})+ return 1+ }+ }+ val wc_opt = viewops.working_copy(v)+ val wc: mut objid.Id = objid.id_none()+ match wc_opt {+ some id => {+ wc = id+ }+ none => {+ msg.info_prefix()+ stdio.print("working copy clean\n", {})+ view.free_view(v)+ store.close(st)+ return 0+ }+ }+ val new_tree_opt = working_tree(st.handles, wc)+ val old_tree_opt = first_parent_tree(st.handles, wc)+ val changes = treediff.compare(st.handles, old_tree_opt, new_tree_opt)+ val conflicted_count: mut usize = 0+ for c in changes {+ val path_view = str.view(c.path.ptr, c.path.len as i64)+ if c.old_kind == treewalk.KIND_MISSING {+ stdio.print("A {s}\n", {path_view})+ } elif c.new_kind == treewalk.KIND_MISSING {+ stdio.print("D {s}\n", {path_view})+ } elif c.new_kind == tree.KIND_CONFLICT {+ stdio.print("C {s}\n", {path_view})+ conflicted_count+++ } else {+ stdio.print("M {s}\n", {path_view})+ }+ }+ if @len(changes) == 0 {+ msg.info_prefix()+ stdio.print("working copy clean\n", {})+ }+ if conflicted_count > 0 {+ stdio.print("{d} conflict(s)\n", {conflicted_count})+ }+ treediff.free(changes)+ view.free_view(v)+ if wc.ptr != none {+ val wp: mut ref void = wc.ptr as ref void+ @free(wp)+ }+ if new_tree_opt is some nt {+ if nt.ptr != none {+ val np: mut ref void = nt.ptr as ref void+ @free(np)+ }+ }+ if old_tree_opt is some ot {+ if ot.ptr != none {+ val op: mut ref void = ot.ptr as ref void+ @free(op)+ }+ }+ store.close(st)+ return 0+}--- /dev/null+++ b/veins/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+++}++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 += 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 += 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/veins/src/core/bytes.sx@@ -0,0 +1,141 @@+/// 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+++ }+ 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+++ }+ 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+++ }+ return true+}--- /dev/null+++ b/veins/src/core/datetime.sx@@ -0,0 +1,83 @@+/// UTC timestamp formatting for log and operation output.++val bytes = use("bytes.sx")+val buf = use("buf.sx")++fn floor_div(a: i64, b: i64) i64 = trust {+ val q: i64 = a / b+ val r: i64 = a % b+ if r != 0 && ((r < 0) != (b < 0)) {+ return q - 1+ }+ return q+}++fn put_pad(b: mut buf.Buf, value: i64, width: usize) void = trust {+ val v: mut i64 = value+ if v < 0 {+ v = 0+ }+ val tmp: ref u8 = @alloc(24) as ref u8+ val n: mut usize = 0+ for v > 0 {+ @store8(@ptradd(tmp, n as i64), (48 + (v % 10)) as u8)+ v = v / 10+ n+++ }+ if n == 0 {+ @store8(@ptradd(tmp, 0), 48)+ n = 1+ }+ val pad: usize = width - n+ val i: mut usize = 0+ for i < pad {+ buf.Buf.put_u8(b, 48)+ i+++ }+ val j: mut usize = n+ for j > 0 {+ j--+ buf.Buf.put_u8(b, @load8(@ptradd(tmp, j as i64)))+ }+ @free(tmp as ref void)+}++pub fn format_utc(seconds: i64) bytes.Bytes = trust {+ val days: i64 = floor_div(seconds, 86400)+ val rem: i64 = seconds - days * 86400+ val hour: i64 = rem / 3600+ val minute: i64 = (rem % 3600) / 60+ val second: i64 = rem % 60+ val z: i64 = days + 719468+ val era: i64 = floor_div(z, 146097)+ val doe: i64 = z - era * 146097+ val yoe: i64 = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365+ val y0: i64 = yoe + era * 400+ val doy: i64 = doe - (365 * yoe + yoe / 4 - yoe / 100)+ val mp: i64 = (5 * doy + 2) / 153+ val d: i64 = doy - (153 * mp + 2) / 5 + 1+ val m0: i64 = mp + 3+ val m: mut i64 = m0+ if mp >= 10 {+ m = mp - 9+ }+ val y: mut i64 = y0+ if m <= 2 {+ y = y + 1+ }+ val b: mut buf.Buf = buf.new(32)+ put_pad(b, y, 4)+ buf.Buf.put_u8(b, 45)+ put_pad(b, m, 2)+ buf.Buf.put_u8(b, 45)+ put_pad(b, d, 2)+ buf.Buf.put_u8(b, 32)+ put_pad(b, hour, 2)+ buf.Buf.put_u8(b, 58)+ put_pad(b, minute, 2)+ buf.Buf.put_u8(b, 58)+ put_pad(b, second, 2)+ val out: bytes.Bytes = bytes.Bytes.dup(buf.Buf.view(b))+ buf.Buf.free(b)+ return out+}--- /dev/null+++ b/veins/src/core/error.sx@@ -0,0 +1,85 @@+/// 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/veins/src/core/identity.sx@@ -0,0 +1,137 @@+/// Author/committer identity from the local config or environment.++val str = use("std/string")+val os = use("std/os")+val time = use("std/time")+val bytes = use("../core/bytes.sx")+val prim = use("../core/primitives.sx")+val layout = use("../store/layout.sx")+val files = use("../io/files.sx")++fn trim(b: bytes.Bytes) bytes.Bytes = trust {+ val start: mut usize = 0+ val end: mut usize = b.len+ for start < end {+ val c: u8 = bytes.Bytes.at(b, start)+ if c != 32 && c != 9 && c != 13 && c != 10 {+ break+ }+ start+++ }+ for end > start {+ val c2: u8 = bytes.Bytes.at(b, end - 1)+ if c2 != 32 && c2 != 9 && c2 != 13 && c2 != 10 {+ break+ }+ end--+ }+ return bytes.Bytes.slice(b, start, end)+}++fn config_value(repo: layout.Repo, key: bytes.Bytes) option[bytes.Bytes] = trust {+ val path: str.StringView = layout.config_path(repo)+ val data_opt = files.read_all(path)+ files.free_path(path)+ if data_opt is some data {+ val pos: mut usize = 0+ val start: mut usize = 0+ for pos <= data.len {+ val at_end: bool = pos == data.len+ if at_end || bytes.Bytes.at(data, pos) == 10 {+ val line: bytes.Bytes = trim(bytes.Bytes.slice(data, start, pos))+ if line.len > 0 && bytes.Bytes.at(line, 0) != 35 {+ val eq: mut i64 = -1+ val i: mut usize = 0+ for i < line.len {+ if bytes.Bytes.at(line, i) == 61 {+ if eq < 0 {+ eq = i as i64+ }+ }+ i+++ }+ if eq >= 0 {+ val k: bytes.Bytes = trim(bytes.Bytes.slice(line, 0, eq as usize))+ if bytes.Bytes.eql(k, key) {+ val v: bytes.Bytes = trim(+ bytes.Bytes.slice(line, eq as usize + 1, line.len)+ )+ val out: bytes.Bytes = bytes.Bytes.dup(v)+ files.free_buffer(data)+ return some out+ }+ }+ }+ start = pos + 1+ }+ pos+++ }+ files.free_buffer(data)+ }+ return none+}++fn env_dup(name: ref u8) option[bytes.Bytes] = trust {+ val v = os.env(name)+ match v {+ some s => {+ return some bytes.Bytes.dup(bytes.from_cstr(s))+ }+ none => {+ return none+ }+ }+}++fn first_config(+ repo: layout.Repo,+ key: bytes.Bytes,+ env1: ref u8,+ env2: ref u8+) bytes.Bytes = trust {+ val c = config_value(repo, key)+ if c is some v {+ return v+ }+ val e1 = env_dup(env1)+ if e1 is some v {+ return v+ }+ val e2 = env_dup(env2)+ if e2 is some v {+ return v+ }+ return bytes.Bytes.dup(bytes.bytes(c"unknown", 7))+}++pub fn signature(repo: layout.Repo) prim.Sig = trust {+ val name: bytes.Bytes = first_config(+ repo,+ bytes.bytes(c"user.name", 9),+ c"GIT_AUTHOR_NAME",+ c"USER"+ )+ val email: bytes.Bytes = first_config(+ repo,+ bytes.bytes(c"user.email", 10),+ c"GIT_AUTHOR_EMAIL",+ c"EMAIL"+ )+ return prim.Sig{+ name: name,+ email: email,+ seconds: time.unix_now(),+ tz_min: 0+ }+}++pub fn free_sig(s: prim.Sig) void = trust {+ if s.name.ptr != none {+ val np: mut ref void = s.name.ptr as ref void+ @free(np)+ }+ if s.email.ptr != none {+ val ep: mut ref void = s.email.ptr as ref void+ @free(ep)+ }+}--- /dev/null+++ b/veins/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/veins/src/core/msg.sx@@ -0,0 +1,27 @@+/// User-facing log messages with consistent level prefixes and colors.++val stdio = use("std/stdio")+val terminal = use("std/terminal")++/// Print a red, bold `error:` prefix to stderr.+pub fn error_prefix() void = trust {+ terminal.eprint_styled("error", terminal.Color.Red, terminal.Color.Default, terminal.Style.Bold)+ stdio.eprint(": ", {})+}++/// Print a yellow, bold `warning:` prefix to stderr.+pub fn warning_prefix() void = trust {+ terminal.eprint_styled(+ "warning",+ terminal.Color.Yellow,+ terminal.Color.Default,+ terminal.Style.Bold+ )+ stdio.eprint(": ", {})+}++/// Print a cyan `info:` prefix to stdout.+pub fn info_prefix() void = trust {+ terminal.print_styled("info", terminal.Color.Cyan, terminal.Color.Default, terminal.Style.Plain)+ stdio.print(": ", {})+}--- /dev/null+++ b/veins/src/core/primitives.sx@@ -0,0 +1,30 @@+/// 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/veins/src/core/reader.sx@@ -0,0 +1,189 @@+/// 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+++ 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 += 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 += 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 += 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 += 7+ i+++ }+ 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 += 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/veins/src/crypto/blake3.sx@@ -0,0 +1,374 @@+/// 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+++ }++ 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+++ }+}++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+++ }+}++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+++ }++ @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+++ }+}++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)+}++extern (C) fn veins_blake3(data: ref u8, len: usize, out: ref u8) void = "veins_blake3"+extern (C) fn veins_blake3_state_size() usize = "veins_blake3_state_size"+extern (C) fn veins_blake3_init(state: ref void) void = "veins_blake3_init"+extern (C) fn veins_blake3_update(+ state: ref void,+ data: ref u8,+ len: usize+) void = "veins_blake3_update"+extern (C) fn veins_blake3_final(state: ref void, out: ref u8) void = "veins_blake3_final"++pub fn hasher_state_size() usize = trust {+ return veins_blake3_state_size()+}++pub fn hasher_init(state: ref void) void = trust {+ veins_blake3_init(state)+}++pub fn hasher_update(state: ref void, data: ref u8, len: usize) void = trust {+ veins_blake3_update(state, data, len)+}++pub fn hasher_final(state: ref void, out: ref u8) void = trust {+ veins_blake3_final(state, out)+}++/// Hash `len` bytes at `data` and write the 32-byte digest to `out`.+///+/// The production build links the scalar C implementation. The pure+/// implementation below is retained for format tests and fallback use.+pub fn hash(data: ref u8, len: usize, out: ref u8) void = trust {+ veins_blake3(data, len, out)+}++pub fn hash_pure(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--+ 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+++ i+++ }++ 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--+ 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+++ }++ @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/veins/src/crypto/blake3/LICENSE_A2@@ -0,0 +1,202 @@++ Apache License+ Version 2.0, January 2004+ http://www.apache.org/licenses/++ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION++ 1. Definitions.++ "License" shall mean the terms and conditions for use, reproduction,+ and distribution as defined by Sections 1 through 9 of this document.++ "Licensor" shall mean the copyright owner or entity authorized by+ the copyright owner that is granting the License.++ "Legal Entity" shall mean the union of the acting entity and all+ other entities that control, are controlled by, or are under common+ control with that entity. For the purposes of this definition,+ "control" means (i) the power, direct or indirect, to cause the+ direction or management of such entity, whether by contract or+ otherwise, or (ii) ownership of fifty percent (50%) or more of the+ outstanding shares, or (iii) beneficial ownership of such entity.++ "You" (or "Your") shall mean an individual or Legal Entity+ exercising permissions granted by this License.++ "Source" form shall mean the preferred form for making modifications,+ including but not limited to software source code, documentation+ source, and configuration files.++ "Object" form shall mean any form resulting from mechanical+ transformation or translation of a Source form, including but+ not limited to compiled object code, generated documentation,+ and conversions to other media types.++ "Work" shall mean the work of authorship, whether in Source or+ Object form, made available under the License, as indicated by a+ copyright notice that is included in or attached to the work+ (an example is provided in the Appendix below).++ "Derivative Works" shall mean any work, whether in Source or Object+ form, that is based on (or derived from) the Work and for which the+ editorial revisions, annotations, elaborations, or other modifications+ represent, as a whole, an original work of authorship. For the purposes+ of this License, Derivative Works shall not include works that remain+ separable from, or merely link (or bind by name) to the interfaces of,+ the Work and Derivative Works thereof.++ "Contribution" shall mean any work of authorship, including+ the original version of the Work and any modifications or additions+ to that Work or Derivative Works thereof, that is intentionally+ submitted to Licensor for inclusion in the Work by the copyright owner+ or by an individual or Legal Entity authorized to submit on behalf of+ the copyright owner. For the purposes of this definition, "submitted"+ means any form of electronic, verbal, or written communication sent+ to the Licensor or its representatives, including but not limited to+ communication on electronic mailing lists, source code control systems,+ and issue tracking systems that are managed by, or on behalf of, the+ Licensor for the purpose of discussing and improving the Work, but+ excluding communication that is conspicuously marked or otherwise+ designated in writing by the copyright owner as "Not a Contribution."++ "Contributor" shall mean Licensor and any individual or Legal Entity+ on behalf of whom a Contribution has been received by Licensor and+ subsequently incorporated within the Work.++ 2. Grant of Copyright License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ copyright license to reproduce, prepare Derivative Works of,+ publicly display, publicly perform, sublicense, and distribute the+ Work and such Derivative Works in Source or Object form.++ 3. Grant of Patent License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ (except as stated in this section) patent license to make, have made,+ use, offer to sell, sell, import, and otherwise transfer the Work,+ where such license applies only to those patent claims licensable+ by such Contributor that are necessarily infringed by their+ Contribution(s) alone or by combination of their Contribution(s)+ with the Work to which such Contribution(s) was submitted. If You+ institute patent litigation against any entity (including a+ cross-claim or counterclaim in a lawsuit) alleging that the Work+ or a Contribution incorporated within the Work constitutes direct+ or contributory patent infringement, then any patent licenses+ granted to You under this License for that Work shall terminate+ as of the date such litigation is filed.++ 4. Redistribution. You may reproduce and distribute copies of the+ Work or Derivative Works thereof in any medium, with or without+ modifications, and in Source or Object form, provided that You+ meet the following conditions:++ (a) You must give any other recipients of the Work or+ Derivative Works a copy of this License; and++ (b) You must cause any modified files to carry prominent notices+ stating that You changed the files; and++ (c) You must retain, in the Source form of any Derivative Works+ that You distribute, all copyright, patent, trademark, and+ attribution notices from the Source form of the Work,+ excluding those notices that do not pertain to any part of+ the Derivative Works; and++ (d) If the Work includes a "NOTICE" text file as part of its+ distribution, then any Derivative Works that You distribute must+ include a readable copy of the attribution notices contained+ within such NOTICE file, excluding those notices that do not+ pertain to any part of the Derivative Works, in at least one+ of the following places: within a NOTICE text file distributed+ as part of the Derivative Works; within the Source form or+ documentation, if provided along with the Derivative Works; or,+ within a display generated by the Derivative Works, if and+ wherever such third-party notices normally appear. The contents+ of the NOTICE file are for informational purposes only and+ do not modify the License. You may add Your own attribution+ notices within Derivative Works that You distribute, alongside+ or as an addendum to the NOTICE text from the Work, provided+ that such additional attribution notices cannot be construed+ as modifying the License.++ You may add Your own copyright statement to Your modifications and+ may provide additional or different license terms and conditions+ for use, reproduction, or distribution of Your modifications, or+ for any such Derivative Works as a whole, provided Your use,+ reproduction, and distribution of the Work otherwise complies with+ the conditions stated in this License.++ 5. Submission of Contributions. Unless You explicitly state otherwise,+ any Contribution intentionally submitted for inclusion in the Work+ by You to the Licensor shall be under the terms and conditions of+ this License, without any additional terms or conditions.+ Notwithstanding the above, nothing herein shall supersede or modify+ the terms of any separate license agreement you may have executed+ with Licensor regarding such Contributions.++ 6. Trademarks. This License does not grant permission to use the trade+ names, trademarks, service marks, or product names of the Licensor,+ except as required for reasonable and customary use in describing the+ origin of the Work and reproducing the content of the NOTICE file.++ 7. Disclaimer of Warranty. Unless required by applicable law or+ agreed to in writing, Licensor provides the Work (and each+ Contributor provides its Contributions) on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or+ implied, including, without limitation, any warranties or conditions+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A+ PARTICULAR PURPOSE. You are solely responsible for determining the+ appropriateness of using or redistributing the Work and assume any+ risks associated with Your exercise of permissions under this License.++ 8. Limitation of Liability. In no event and under no legal theory,+ whether in tort (including negligence), contract, or otherwise,+ unless required by applicable law (such as deliberate and grossly+ negligent acts) or agreed to in writing, shall any Contributor be+ liable to You for damages, including any direct, indirect, special,+ incidental, or consequential damages of any character arising as a+ result of this License or out of the use or inability to use the+ Work (including but not limited to damages for loss of goodwill,+ work stoppage, computer failure or malfunction, or any and all+ other commercial damages or losses), even if such Contributor+ has been advised of the possibility of such damages.++ 9. Accepting Warranty or Additional Liability. While redistributing+ the Work or Derivative Works thereof, You may choose to offer,+ and charge a fee for, acceptance of support, warranty, indemnity,+ or other liability obligations and/or rights consistent with this+ License. However, in accepting such obligations, You may act only+ on Your own behalf and on Your sole responsibility, not on behalf+ of any other Contributor, and only if You agree to indemnify,+ defend, and hold each Contributor harmless for any liability+ incurred by, or claims asserted against, such Contributor by reason+ of your accepting any such warranty or additional liability.++ END OF TERMS AND CONDITIONS++ APPENDIX: How to apply the Apache License to your work.++ To apply the Apache License to your work, attach the following+ boilerplate notice, with the fields enclosed by brackets "[]"+ replaced with your own identifying information. (Don't include+ the brackets!) The text should be enclosed in the appropriate+ comment syntax for the file format. We also recommend that a+ file or class name and description of purpose be included on the+ same "printed page" as the copyright notice for easier+ identification within third-party archives.++ Copyright 2019 Jack O'Connor and Samuel Neves++ Licensed under the Apache License, Version 2.0 (the "License");+ you may not use this file except in compliance with the License.+ You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing, software+ distributed under the License is distributed on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ See the License for the specific language governing permissions and+ limitations under the License.--- /dev/null+++ b/veins/src/crypto/blake3/LICENSE_A2LLVM@@ -0,0 +1,219 @@+ Apache License+ Version 2.0, January 2004+ http://www.apache.org/licenses/++ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION++ 1. Definitions.++ "License" shall mean the terms and conditions for use, reproduction,+ and distribution as defined by Sections 1 through 9 of this document.++ "Licensor" shall mean the copyright owner or entity authorized by+ the copyright owner that is granting the License.++ "Legal Entity" shall mean the union of the acting entity and all+ other entities that control, are controlled by, or are under common+ control with that entity. For the purposes of this definition,+ "control" means (i) the power, direct or indirect, to cause the+ direction or management of such entity, whether by contract or+ otherwise, or (ii) ownership of fifty percent (50%) or more of the+ outstanding shares, or (iii) beneficial ownership of such entity.++ "You" (or "Your") shall mean an individual or Legal Entity+ exercising permissions granted by this License.++ "Source" form shall mean the preferred form for making modifications,+ including but not limited to software source code, documentation+ source, and configuration files.++ "Object" form shall mean any form resulting from mechanical+ transformation or translation of a Source form, including but+ not limited to compiled object code, generated documentation,+ and conversions to other media types.++ "Work" shall mean the work of authorship, whether in Source or+ Object form, made available under the License, as indicated by a+ copyright notice that is included in or attached to the work+ (an example is provided in the Appendix below).++ "Derivative Works" shall mean any work, whether in Source or Object+ form, that is based on (or derived from) the Work and for which the+ editorial revisions, annotations, elaborations, or other modifications+ represent, as a whole, an original work of authorship. For the purposes+ of this License, Derivative Works shall not include works that remain+ separable from, or merely link (or bind by name) to the interfaces of,+ the Work and Derivative Works thereof.++ "Contribution" shall mean any work of authorship, including+ the original version of the Work and any modifications or additions+ to that Work or Derivative Works thereof, that is intentionally+ submitted to Licensor for inclusion in the Work by the copyright owner+ or by an individual or Legal Entity authorized to submit on behalf of+ the copyright owner. For the purposes of this definition, "submitted"+ means any form of electronic, verbal, or written communication sent+ to the Licensor or its representatives, including but not limited to+ communication on electronic mailing lists, source code control systems,+ and issue tracking systems that are managed by, or on behalf of, the+ Licensor for the purpose of discussing and improving the Work, but+ excluding communication that is conspicuously marked or otherwise+ designated in writing by the copyright owner as "Not a Contribution."++ "Contributor" shall mean Licensor and any individual or Legal Entity+ on behalf of whom a Contribution has been received by Licensor and+ subsequently incorporated within the Work.++ 2. Grant of Copyright License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ copyright license to reproduce, prepare Derivative Works of,+ publicly display, publicly perform, sublicense, and distribute the+ Work and such Derivative Works in Source or Object form.++ 3. Grant of Patent License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ (except as stated in this section) patent license to make, have made,+ use, offer to sell, sell, import, and otherwise transfer the Work,+ where such license applies only to those patent claims licensable+ by such Contributor that are necessarily infringed by their+ Contribution(s) alone or by combination of their Contribution(s)+ with the Work to which such Contribution(s) was submitted. If You+ institute patent litigation against any entity (including a+ cross-claim or counterclaim in a lawsuit) alleging that the Work+ or a Contribution incorporated within the Work constitutes direct+ or contributory patent infringement, then any patent licenses+ granted to You under this License for that Work shall terminate+ as of the date such litigation is filed.++ 4. Redistribution. You may reproduce and distribute copies of the+ Work or Derivative Works thereof in any medium, with or without+ modifications, and in Source or Object form, provided that You+ meet the following conditions:++ (a) You must give any other recipients of the Work or+ Derivative Works a copy of this License; and++ (b) You must cause any modified files to carry prominent notices+ stating that You changed the files; and++ (c) You must retain, in the Source form of any Derivative Works+ that You distribute, all copyright, patent, trademark, and+ attribution notices from the Source form of the Work,+ excluding those notices that do not pertain to any part of+ the Derivative Works; and++ (d) If the Work includes a "NOTICE" text file as part of its+ distribution, then any Derivative Works that You distribute must+ include a readable copy of the attribution notices contained+ within such NOTICE file, excluding those notices that do not+ pertain to any part of the Derivative Works, in at least one+ of the following places: within a NOTICE text file distributed+ as part of the Derivative Works; within the Source form or+ documentation, if provided along with the Derivative Works; or,+ within a display generated by the Derivative Works, if and+ wherever such third-party notices normally appear. The contents+ of the NOTICE file are for informational purposes only and+ do not modify the License. You may add Your own attribution+ notices within Derivative Works that You distribute, alongside+ or as an addendum to the NOTICE text from the Work, provided+ that such additional attribution notices cannot be construed+ as modifying the License.++ You may add Your own copyright statement to Your modifications and+ may provide additional or different license terms and conditions+ for use, reproduction, or distribution of Your modifications, or+ for any such Derivative Works as a whole, provided Your use,+ reproduction, and distribution of the Work otherwise complies with+ the conditions stated in this License.++ 5. Submission of Contributions. Unless You explicitly state otherwise,+ any Contribution intentionally submitted for inclusion in the Work+ by You to the Licensor shall be under the terms and conditions of+ this License, without any additional terms or conditions.+ Notwithstanding the above, nothing herein shall supersede or modify+ the terms of any separate license agreement you may have executed+ with Licensor regarding such Contributions.++ 6. Trademarks. This License does not grant permission to use the trade+ names, trademarks, service marks, or product names of the Licensor,+ except as required for reasonable and customary use in describing the+ origin of the Work and reproducing the content of the NOTICE file.++ 7. Disclaimer of Warranty. Unless required by applicable law or+ agreed to in writing, Licensor provides the Work (and each+ Contributor provides its Contributions) on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or+ implied, including, without limitation, any warranties or conditions+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A+ PARTICULAR PURPOSE. You are solely responsible for determining the+ appropriateness of using or redistributing the Work and assume any+ risks associated with Your exercise of permissions under this License.++ 8. Limitation of Liability. In no event and under no legal theory,+ whether in tort (including negligence), contract, or otherwise,+ unless required by applicable law (such as deliberate and grossly+ negligent acts) or agreed to in writing, shall any Contributor be+ liable to You for damages, including any direct, indirect, special,+ incidental, or consequential damages of any character arising as a+ result of this License or out of the use or inability to use the+ Work (including but not limited to damages for loss of goodwill,+ work stoppage, computer failure or malfunction, or any and all+ other commercial damages or losses), even if such Contributor+ has been advised of the possibility of such damages.++ 9. Accepting Warranty or Additional Liability. While redistributing+ the Work or Derivative Works thereof, You may choose to offer,+ and charge a fee for, acceptance of support, warranty, indemnity,+ or other liability obligations and/or rights consistent with this+ License. However, in accepting such obligations, You may act only+ on Your own behalf and on Your sole responsibility, not on behalf+ of any other Contributor, and only if You agree to indemnify,+ defend, and hold each Contributor harmless for any liability+ incurred by, or claims asserted against, such Contributor by reason+ of your accepting any such warranty or additional liability.++ END OF TERMS AND CONDITIONS++ APPENDIX: How to apply the Apache License to your work.++ To apply the Apache License to your work, attach the following+ boilerplate notice, with the fields enclosed by brackets "[]"+ replaced with your own identifying information. (Don't include+ the brackets!) The text should be enclosed in the appropriate+ comment syntax for the file format. We also recommend that a+ file or class name and description of purpose be included on the+ same "printed page" as the copyright notice for easier+ identification within third-party archives.++ Copyright 2019 Jack O'Connor and Samuel Neves++ Licensed under the Apache License, Version 2.0 (the "License");+ you may not use this file except in compliance with the License.+ You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing, software+ distributed under the License is distributed on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ See the License for the specific language governing permissions and+ limitations under the License.+++---- LLVM Exceptions to the Apache 2.0 License ----++As an exception, if, as a result of your compiling your source code, portions+of this Software are embedded into an Object form of such source code, you+may redistribute such embedded portions in such Object form without complying+with the conditions of Sections 4(a), 4(b) and 4(d) of the License.++In addition, if you combine or link compiled forms of this Software with+software that is licensed under the GPLv2 ("Combined Software") and if a+court of competent jurisdiction determines that the patent provision (Section+3), the indemnity provision (Section 9) or other Section of the License+conflicts with the conditions of the GPLv2, you may retroactively and+prospectively choose to deem waived or otherwise exclude such Section(s) of+the License, but only in their entirety and only with respect to the Combined+Software.+--- /dev/null+++ b/veins/src/crypto/blake3/LICENSE_CC0@@ -0,0 +1,121 @@+Creative Commons Legal Code++CC0 1.0 Universal++ CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE+ LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN+ ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS+ INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES+ REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS+ PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM+ THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED+ HEREUNDER.++Statement of Purpose++The laws of most jurisdictions throughout the world automatically confer+exclusive Copyright and Related Rights (defined below) upon the creator+and subsequent owner(s) (each and all, an "owner") of an original work of+authorship and/or a database (each, a "Work").++Certain owners wish to permanently relinquish those rights to a Work for+the purpose of contributing to a commons of creative, cultural and+scientific works ("Commons") that the public can reliably and without fear+of later claims of infringement build upon, modify, incorporate in other+works, reuse and redistribute as freely as possible in any form whatsoever+and for any purposes, including without limitation commercial purposes.+These owners may contribute to the Commons to promote the ideal of a free+culture and the further production of creative, cultural and scientific+works, or to gain reputation or greater distribution for their Work in+part through the use and efforts of others.++For these and/or other purposes and motivations, and without any+expectation of additional consideration or compensation, the person+associating CC0 with a Work (the "Affirmer"), to the extent that he or she+is an owner of Copyright and Related Rights in the Work, voluntarily+elects to apply CC0 to the Work and publicly distribute the Work under its+terms, with knowledge of his or her Copyright and Related Rights in the+Work and the meaning and intended legal effect of CC0 on those rights.++1. Copyright and Related Rights. A Work made available under CC0 may be+protected by copyright and related or neighboring rights ("Copyright and+Related Rights"). Copyright and Related Rights include, but are not+limited to, the following:++ i. the right to reproduce, adapt, distribute, perform, display,+ communicate, and translate a Work;+ ii. moral rights retained by the original author(s) and/or performer(s);+iii. publicity and privacy rights pertaining to a person's image or+ likeness depicted in a Work;+ iv. rights protecting against unfair competition in regards to a Work,+ subject to the limitations in paragraph 4(a), below;+ v. rights protecting the extraction, dissemination, use and reuse of data+ in a Work;+ vi. database rights (such as those arising under Directive 96/9/EC of the+ European Parliament and of the Council of 11 March 1996 on the legal+ protection of databases, and under any national implementation+ thereof, including any amended or successor version of such+ directive); and+vii. other similar, equivalent or corresponding rights throughout the+ world based on applicable law or treaty, and any national+ implementations thereof.++2. Waiver. To the greatest extent permitted by, but not in contravention+of, applicable law, Affirmer hereby overtly, fully, permanently,+irrevocably and unconditionally waives, abandons, and surrenders all of+Affirmer's Copyright and Related Rights and associated claims and causes+of action, whether now known or unknown (including existing as well as+future claims and causes of action), in the Work (i) in all territories+worldwide, (ii) for the maximum duration provided by applicable law or+treaty (including future time extensions), (iii) in any current or future+medium and for any number of copies, and (iv) for any purpose whatsoever,+including without limitation commercial, advertising or promotional+purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each+member of the public at large and to the detriment of Affirmer's heirs and+successors, fully intending that such Waiver shall not be subject to+revocation, rescission, cancellation, termination, or any other legal or+equitable action to disrupt the quiet enjoyment of the Work by the public+as contemplated by Affirmer's express Statement of Purpose.++3. Public License Fallback. Should any part of the Waiver for any reason+be judged legally invalid or ineffective under applicable law, then the+Waiver shall be preserved to the maximum extent permitted taking into+account Affirmer's express Statement of Purpose. In addition, to the+extent the Waiver is so judged Affirmer hereby grants to each affected+person a royalty-free, non transferable, non sublicensable, non exclusive,+irrevocable and unconditional license to exercise Affirmer's Copyright and+Related Rights in the Work (i) in all territories worldwide, (ii) for the+maximum duration provided by applicable law or treaty (including future+time extensions), (iii) in any current or future medium and for any number+of copies, and (iv) for any purpose whatsoever, including without+limitation commercial, advertising or promotional purposes (the+"License"). The License shall be deemed effective as of the date CC0 was+applied by Affirmer to the Work. Should any part of the License for any+reason be judged legally invalid or ineffective under applicable law, such+partial invalidity or ineffectiveness shall not invalidate the remainder+of the License, and in such case Affirmer hereby affirms that he or she+will not (i) exercise any of his or her remaining Copyright and Related+Rights in the Work or (ii) assert any associated claims and causes of+action with respect to the Work, in either case contrary to Affirmer's+express Statement of Purpose.++4. Limitations and Disclaimers.++ a. No trademark or patent rights held by Affirmer are waived, abandoned,+ surrendered, licensed or otherwise affected by this document.+ b. Affirmer offers the Work as-is and makes no representations or+ warranties of any kind concerning the Work, express, implied,+ statutory or otherwise, including without limitation warranties of+ title, merchantability, fitness for a particular purpose, non+ infringement, or the absence of latent or other defects, accuracy, or+ the present or absence of errors, whether or not discoverable, all to+ the greatest extent permissible under applicable law.+ c. Affirmer disclaims responsibility for clearing rights of other persons+ that may apply to the Work or any use thereof, including without+ limitation any person's Copyright and Related Rights in the Work.+ Further, Affirmer disclaims responsibility for obtaining any necessary+ consents, permissions or other rights required for any use of the+ Work.+ d. Affirmer understands and acknowledges that Creative Commons is not a+ party to this document and has no duty or obligation with respect to+ this CC0 or use of the Work.--- /dev/null+++ b/veins/src/crypto/blake3/blake3.c@@ -0,0 +1,651 @@+#include <assert.h>+#include <stdbool.h>+#include <string.h>+#include <stdint.h>++#include "blake3.h"+#include "blake3_impl.h"++const char *blake3_version(void) { return BLAKE3_VERSION_STRING; }++INLINE void chunk_state_init(blake3_chunk_state *self, const uint32_t key[8],+ uint8_t flags) {+ memcpy(self->cv, key, BLAKE3_KEY_LEN);+ self->chunk_counter = 0;+ memset(self->buf, 0, BLAKE3_BLOCK_LEN);+ self->buf_len = 0;+ self->blocks_compressed = 0;+ self->flags = flags;+}++INLINE void chunk_state_reset(blake3_chunk_state *self, const uint32_t key[8],+ uint64_t chunk_counter) {+ memcpy(self->cv, key, BLAKE3_KEY_LEN);+ self->chunk_counter = chunk_counter;+ self->blocks_compressed = 0;+ memset(self->buf, 0, BLAKE3_BLOCK_LEN);+ self->buf_len = 0;+}++INLINE size_t chunk_state_len(const blake3_chunk_state *self) {+ return (BLAKE3_BLOCK_LEN * (size_t)self->blocks_compressed) ++ ((size_t)self->buf_len);+}++INLINE size_t chunk_state_fill_buf(blake3_chunk_state *self,+ const uint8_t *input, size_t input_len) {+ size_t take = BLAKE3_BLOCK_LEN - ((size_t)self->buf_len);+ if (take > input_len) {+ take = input_len;+ }+ uint8_t *dest = self->buf + ((size_t)self->buf_len);+ memcpy(dest, input, take);+ self->buf_len += (uint8_t)take;+ return take;+}++INLINE uint8_t chunk_state_maybe_start_flag(const blake3_chunk_state *self) {+ if (self->blocks_compressed == 0) {+ return CHUNK_START;+ } else {+ return 0;+ }+}++typedef struct {+ uint32_t input_cv[8];+ uint64_t counter;+ uint8_t block[BLAKE3_BLOCK_LEN];+ uint8_t block_len;+ uint8_t flags;+} output_t;++INLINE output_t make_output(const uint32_t input_cv[8],+ const uint8_t block[BLAKE3_BLOCK_LEN],+ uint8_t block_len, uint64_t counter,+ uint8_t flags) {+ output_t ret;+ memcpy(ret.input_cv, input_cv, 32);+ memcpy(ret.block, block, BLAKE3_BLOCK_LEN);+ ret.block_len = block_len;+ ret.counter = counter;+ ret.flags = flags;+ return ret;+}++// Chaining values within a given chunk (specifically the compress_in_place+// interface) are represented as words. This avoids unnecessary bytes<->words+// conversion overhead in the portable implementation. However, the hash_many+// interface handles both user input and parent node blocks, so it accepts+// bytes. For that reason, chaining values in the CV stack are represented as+// bytes.+INLINE void output_chaining_value(const output_t *self, uint8_t cv[32]) {+ uint32_t cv_words[8];+ memcpy(cv_words, self->input_cv, 32);+ blake3_compress_in_place(cv_words, self->block, self->block_len,+ self->counter, self->flags);+ store_cv_words(cv, cv_words);+}++INLINE void output_root_bytes(const output_t *self, uint64_t seek, uint8_t *out,+ size_t out_len) {+ if (out_len == 0) {+ return;+ }+ uint64_t output_block_counter = seek / 64;+ size_t offset_within_block = seek % 64;+ uint8_t wide_buf[64];+ if(offset_within_block) {+ blake3_compress_xof(self->input_cv, self->block, self->block_len, output_block_counter, self->flags | ROOT, wide_buf);+ const size_t available_bytes = 64 - offset_within_block;+ const size_t bytes = out_len > available_bytes ? available_bytes : out_len;+ memcpy(out, wide_buf + offset_within_block, bytes);+ out += bytes;+ out_len -= bytes;+ output_block_counter += 1;+ }+ if(out_len / 64) {+ blake3_xof_many(self->input_cv, self->block, self->block_len, output_block_counter, self->flags | ROOT, out, out_len / 64);+ }+ output_block_counter += out_len / 64;+ out += out_len & -64;+ out_len -= out_len & -64;+ if(out_len) {+ blake3_compress_xof(self->input_cv, self->block, self->block_len, output_block_counter, self->flags | ROOT, wide_buf);+ memcpy(out, wide_buf, out_len);+ }+}++INLINE void chunk_state_update(blake3_chunk_state *self, const uint8_t *input,+ size_t input_len) {+ if (self->buf_len > 0) {+ size_t take = chunk_state_fill_buf(self, input, input_len);+ input += take;+ input_len -= take;+ if (input_len > 0) {+ blake3_compress_in_place(+ self->cv, self->buf, BLAKE3_BLOCK_LEN, self->chunk_counter,+ self->flags | chunk_state_maybe_start_flag(self));+ self->blocks_compressed += 1;+ self->buf_len = 0;+ memset(self->buf, 0, BLAKE3_BLOCK_LEN);+ }+ }++ while (input_len > BLAKE3_BLOCK_LEN) {+ blake3_compress_in_place(self->cv, input, BLAKE3_BLOCK_LEN,+ self->chunk_counter,+ self->flags | chunk_state_maybe_start_flag(self));+ self->blocks_compressed += 1;+ input += BLAKE3_BLOCK_LEN;+ input_len -= BLAKE3_BLOCK_LEN;+ }++ chunk_state_fill_buf(self, input, input_len);+}++INLINE output_t chunk_state_output(const blake3_chunk_state *self) {+ uint8_t block_flags =+ self->flags | chunk_state_maybe_start_flag(self) | CHUNK_END;+ return make_output(self->cv, self->buf, self->buf_len, self->chunk_counter,+ block_flags);+}++INLINE output_t parent_output(const uint8_t block[BLAKE3_BLOCK_LEN],+ const uint32_t key[8], uint8_t flags) {+ return make_output(key, block, BLAKE3_BLOCK_LEN, 0, flags | PARENT);+}++// Given some input larger than one chunk, return the number of bytes that+// should go in the left subtree. This is the largest power-of-2 number of+// chunks that leaves at least 1 byte for the right subtree.+INLINE size_t left_subtree_len(size_t input_len) {+ // Subtract 1 to reserve at least one byte for the right side. input_len+ // should always be greater than BLAKE3_CHUNK_LEN.+ size_t full_chunks = (input_len - 1) / BLAKE3_CHUNK_LEN;+ return round_down_to_power_of_2(full_chunks) * BLAKE3_CHUNK_LEN;+}++// Use SIMD parallelism to hash up to MAX_SIMD_DEGREE chunks at the same time+// on a single thread. Write out the chunk chaining values and return the+// number of chunks hashed. These chunks are never the root and never empty;+// those cases use a different codepath.+INLINE size_t compress_chunks_parallel(const uint8_t *input, size_t input_len,+ const uint32_t key[8],+ uint64_t chunk_counter, uint8_t flags,+ uint8_t *out) {+#if defined(BLAKE3_TESTING)+ assert(0 < input_len);+ assert(input_len <= MAX_SIMD_DEGREE * BLAKE3_CHUNK_LEN);+#endif++ const uint8_t *chunks_array[MAX_SIMD_DEGREE];+ size_t input_position = 0;+ size_t chunks_array_len = 0;+ while (input_len - input_position >= BLAKE3_CHUNK_LEN) {+ chunks_array[chunks_array_len] = &input[input_position];+ input_position += BLAKE3_CHUNK_LEN;+ chunks_array_len += 1;+ }++ blake3_hash_many(chunks_array, chunks_array_len,+ BLAKE3_CHUNK_LEN / BLAKE3_BLOCK_LEN, key, chunk_counter,+ true, flags, CHUNK_START, CHUNK_END, out);++ // Hash the remaining partial chunk, if there is one. Note that the empty+ // chunk (meaning the empty message) is a different codepath.+ if (input_len > input_position) {+ uint64_t counter = chunk_counter + (uint64_t)chunks_array_len;+ blake3_chunk_state chunk_state;+ chunk_state_init(&chunk_state, key, flags);+ chunk_state.chunk_counter = counter;+ chunk_state_update(&chunk_state, &input[input_position],+ input_len - input_position);+ output_t output = chunk_state_output(&chunk_state);+ output_chaining_value(&output, &out[chunks_array_len * BLAKE3_OUT_LEN]);+ return chunks_array_len + 1;+ } else {+ return chunks_array_len;+ }+}++// Use SIMD parallelism to hash up to MAX_SIMD_DEGREE parents at the same time+// on a single thread. Write out the parent chaining values and return the+// number of parents hashed. (If there's an odd input chaining value left over,+// return it as an additional output.) These parents are never the root and+// never empty; those cases use a different codepath.+INLINE size_t compress_parents_parallel(const uint8_t *child_chaining_values,+ size_t num_chaining_values,+ const uint32_t key[8], uint8_t flags,+ uint8_t *out) {+#if defined(BLAKE3_TESTING)+ assert(2 <= num_chaining_values);+ assert(num_chaining_values <= 2 * MAX_SIMD_DEGREE_OR_2);+#endif++ const uint8_t *parents_array[MAX_SIMD_DEGREE_OR_2];+ size_t parents_array_len = 0;+ while (num_chaining_values - (2 * parents_array_len) >= 2) {+ parents_array[parents_array_len] =+ &child_chaining_values[2 * parents_array_len * BLAKE3_OUT_LEN];+ parents_array_len += 1;+ }++ blake3_hash_many(parents_array, parents_array_len, 1, key,+ 0, // Parents always use counter 0.+ false, flags | PARENT,+ 0, // Parents have no start flags.+ 0, // Parents have no end flags.+ out);++ // If there's an odd child left over, it becomes an output.+ if (num_chaining_values > 2 * parents_array_len) {+ memcpy(&out[parents_array_len * BLAKE3_OUT_LEN],+ &child_chaining_values[2 * parents_array_len * BLAKE3_OUT_LEN],+ BLAKE3_OUT_LEN);+ return parents_array_len + 1;+ } else {+ return parents_array_len;+ }+}++// The wide helper function returns (writes out) an array of chaining values+// and returns the length of that array. The number of chaining values returned+// is the dynamically detected SIMD degree, at most MAX_SIMD_DEGREE. Or fewer,+// if the input is shorter than that many chunks. The reason for maintaining a+// wide array of chaining values going back up the tree, is to allow the+// implementation to hash as many parents in parallel as possible.+//+// As a special case when the SIMD degree is 1, this function will still return+// at least 2 outputs. This guarantees that this function doesn't perform the+// root compression. (If it did, it would use the wrong flags, and also we+// wouldn't be able to implement extendable output.) Note that this function is+// not used when the whole input is only 1 chunk long; that's a different+// codepath.+//+// Why not just have the caller split the input on the first update(), instead+// of implementing this special rule? Because we don't want to limit SIMD or+// multi-threading parallelism for that update().+size_t blake3_compress_subtree_wide(const uint8_t *input, size_t input_len,+ const uint32_t key[8],+ uint64_t chunk_counter, uint8_t flags,+ uint8_t *out, bool use_tbb) {+ // Note that the single chunk case does *not* bump the SIMD degree up to 2+ // when it is 1. If this implementation adds multi-threading in the future,+ // this gives us the option of multi-threading even the 2-chunk case, which+ // can help performance on smaller platforms.+ if (input_len <= blake3_simd_degree() * BLAKE3_CHUNK_LEN) {+ return compress_chunks_parallel(input, input_len, key, chunk_counter, flags,+ out);+ }++ // With more than simd_degree chunks, we need to recurse. Start by dividing+ // the input into left and right subtrees. (Note that this is only optimal+ // as long as the SIMD degree is a power of 2. If we ever get a SIMD degree+ // of 3 or something, we'll need a more complicated strategy.)+ size_t left_input_len = left_subtree_len(input_len);+ size_t right_input_len = input_len - left_input_len;+ const uint8_t *right_input = &input[left_input_len];+ uint64_t right_chunk_counter =+ chunk_counter + (uint64_t)(left_input_len / BLAKE3_CHUNK_LEN);++ // Make space for the child outputs. Here we use MAX_SIMD_DEGREE_OR_2 to+ // account for the special case of returning 2 outputs when the SIMD degree+ // is 1.+ uint8_t cv_array[2 * MAX_SIMD_DEGREE_OR_2 * BLAKE3_OUT_LEN];+ size_t degree = blake3_simd_degree();+ if (left_input_len > BLAKE3_CHUNK_LEN && degree == 1) {+ // The special case: We always use a degree of at least two, to make+ // sure there are two outputs. Except, as noted above, at the chunk+ // level, where we allow degree=1. (Note that the 1-chunk-input case is+ // a different codepath.)+ degree = 2;+ }+ uint8_t *right_cvs = &cv_array[degree * BLAKE3_OUT_LEN];++ // Recurse!+ size_t left_n = SIZE_MAX;+ size_t right_n = SIZE_MAX;++#if defined(BLAKE3_USE_TBB)+ blake3_compress_subtree_wide_join_tbb(+ key, flags, use_tbb,+ // left-hand side+ input, left_input_len, chunk_counter, cv_array, &left_n,+ // right-hand side+ right_input, right_input_len, right_chunk_counter, right_cvs, &right_n);+#else+ left_n = blake3_compress_subtree_wide(+ input, left_input_len, key, chunk_counter, flags, cv_array, use_tbb);+ right_n = blake3_compress_subtree_wide(right_input, right_input_len, key,+ right_chunk_counter, flags, right_cvs,+ use_tbb);+#endif // BLAKE3_USE_TBB++ // The special case again. If simd_degree=1, then we'll have left_n=1 and+ // right_n=1. Rather than compressing them into a single output, return+ // them directly, to make sure we always have at least two outputs.+ if (left_n == 1) {+ memcpy(out, cv_array, 2 * BLAKE3_OUT_LEN);+ return 2;+ }++ // Otherwise, do one layer of parent node compression.+ size_t num_chaining_values = left_n + right_n;+ return compress_parents_parallel(cv_array, num_chaining_values, key, flags,+ out);+}++// Hash a subtree with compress_subtree_wide(), and then condense the resulting+// list of chaining values down to a single parent node. Don't compress that+// last parent node, however. Instead, return its message bytes (the+// concatenated chaining values of its children). This is necessary when the+// first call to update() supplies a complete subtree, because the topmost+// parent node of that subtree could end up being the root. It's also necessary+// for extended output in the general case.+//+// As with compress_subtree_wide(), this function is not used on inputs of 1+// chunk or less. That's a different codepath.+INLINE void+compress_subtree_to_parent_node(const uint8_t *input, size_t input_len,+ const uint32_t key[8], uint64_t chunk_counter,+ uint8_t flags, uint8_t out[2 * BLAKE3_OUT_LEN],+ bool use_tbb) {+#if defined(BLAKE3_TESTING)+ assert(input_len > BLAKE3_CHUNK_LEN);+#endif++ uint8_t cv_array[MAX_SIMD_DEGREE_OR_2 * BLAKE3_OUT_LEN];+ size_t num_cvs = blake3_compress_subtree_wide(input, input_len, key,+ chunk_counter, flags, cv_array, use_tbb);+ assert(num_cvs <= MAX_SIMD_DEGREE_OR_2);+ // The following loop never executes when MAX_SIMD_DEGREE_OR_2 is 2, because+ // as we just asserted, num_cvs will always be <=2 in that case. But GCC+ // (particularly GCC 8.5) can't tell that it never executes, and if NDEBUG is+ // set then it emits incorrect warnings here. We tried a few different+ // hacks to silence these, but in the end our hacks just produced different+ // warnings (see https://github.com/BLAKE3-team/BLAKE3/pull/380). Out of+ // desperation, we ifdef out this entire loop when we know it's not needed.+#if MAX_SIMD_DEGREE_OR_2 > 2+ // If MAX_SIMD_DEGREE_OR_2 is greater than 2 and there's enough input,+ // compress_subtree_wide() returns more than 2 chaining values. Condense+ // them into 2 by forming parent nodes repeatedly.+ uint8_t out_array[MAX_SIMD_DEGREE_OR_2 * BLAKE3_OUT_LEN / 2];+ while (num_cvs > 2) {+ num_cvs =+ compress_parents_parallel(cv_array, num_cvs, key, flags, out_array);+ memcpy(cv_array, out_array, num_cvs * BLAKE3_OUT_LEN);+ }+#endif+ memcpy(out, cv_array, 2 * BLAKE3_OUT_LEN);+}++INLINE void hasher_init_base(blake3_hasher *self, const uint32_t key[8],+ uint8_t flags) {+ memcpy(self->key, key, BLAKE3_KEY_LEN);+ chunk_state_init(&self->chunk, key, flags);+ self->cv_stack_len = 0;+}++void blake3_hasher_init(blake3_hasher *self) { hasher_init_base(self, IV, 0); }++void blake3_hasher_init_keyed(blake3_hasher *self,+ const uint8_t key[BLAKE3_KEY_LEN]) {+ uint32_t key_words[8];+ load_key_words(key, key_words);+ hasher_init_base(self, key_words, KEYED_HASH);+}++void blake3_hasher_init_derive_key_raw(blake3_hasher *self, const void *context,+ size_t context_len) {+ blake3_hasher context_hasher;+ hasher_init_base(&context_hasher, IV, DERIVE_KEY_CONTEXT);+ blake3_hasher_update(&context_hasher, context, context_len);+ uint8_t context_key[BLAKE3_KEY_LEN];+ blake3_hasher_finalize(&context_hasher, context_key, BLAKE3_KEY_LEN);+ uint32_t context_key_words[8];+ load_key_words(context_key, context_key_words);+ hasher_init_base(self, context_key_words, DERIVE_KEY_MATERIAL);+}++void blake3_hasher_init_derive_key(blake3_hasher *self, const char *context) {+ blake3_hasher_init_derive_key_raw(self, context, strlen(context));+}++// As described in hasher_push_cv() below, we do "lazy merging", delaying+// merges until right before the next CV is about to be added. This is+// different from the reference implementation. Another difference is that we+// aren't always merging 1 chunk at a time. Instead, each CV might represent+// any power-of-two number of chunks, as long as the smaller-above-larger stack+// order is maintained. Instead of the "count the trailing 0-bits" algorithm+// described in the spec, we use a "count the total number of 1-bits" variant+// that doesn't require us to retain the subtree size of the CV on top of the+// stack. The principle is the same: each CV that should remain in the stack is+// represented by a 1-bit in the total number of chunks (or bytes) so far.+INLINE void hasher_merge_cv_stack(blake3_hasher *self, uint64_t total_len) {+ size_t post_merge_stack_len = (size_t)popcnt(total_len);+ while (self->cv_stack_len > post_merge_stack_len) {+ uint8_t *parent_node =+ &self->cv_stack[(self->cv_stack_len - 2) * BLAKE3_OUT_LEN];+ output_t output = parent_output(parent_node, self->key, self->chunk.flags);+ output_chaining_value(&output, parent_node);+ self->cv_stack_len -= 1;+ }+}++// In reference_impl.rs, we merge the new CV with existing CVs from the stack+// before pushing it. We can do that because we know more input is coming, so+// we know none of the merges are root.+//+// This setting is different. We want to feed as much input as possible to+// compress_subtree_wide(), without setting aside anything for the chunk_state.+// If the user gives us 64 KiB, we want to parallelize over all 64 KiB at once+// as a single subtree, if at all possible.+//+// This leads to two problems:+// 1) This 64 KiB input might be the only call that ever gets made to update.+// In this case, the root node of the 64 KiB subtree would be the root node+// of the whole tree, and it would need to be ROOT finalized. We can't+// compress it until we know.+// 2) This 64 KiB input might complete a larger tree, whose root node is+// similarly going to be the root of the whole tree. For example, maybe+// we have 196 KiB (that is, 128 + 64) hashed so far. We can't compress the+// node at the root of the 256 KiB subtree until we know how to finalize it.+//+// The second problem is solved with "lazy merging". That is, when we're about+// to add a CV to the stack, we don't merge it with anything first, as the+// reference impl does. Instead we do merges using the *previous* CV that was+// added, which is sitting on top of the stack, and we put the new CV+// (unmerged) on top of the stack afterwards. This guarantees that we never+// merge the root node until finalize().+//+// Solving the first problem requires an additional tool,+// compress_subtree_to_parent_node(). That function always returns the top+// *two* chaining values of the subtree it's compressing. We then do lazy+// merging with each of them separately, so that the second CV will always+// remain unmerged. (That also helps us support extendable output when we're+// hashing an input all-at-once.)+INLINE void hasher_push_cv(blake3_hasher *self, uint8_t new_cv[BLAKE3_OUT_LEN],+ uint64_t chunk_counter) {+ hasher_merge_cv_stack(self, chunk_counter);+ memcpy(&self->cv_stack[self->cv_stack_len * BLAKE3_OUT_LEN], new_cv,+ BLAKE3_OUT_LEN);+ self->cv_stack_len += 1;+}++INLINE void blake3_hasher_update_base(blake3_hasher *self, const void *input,+ size_t input_len, bool use_tbb) {+ // Explicitly checking for zero avoids causing UB by passing a null pointer+ // to memcpy. This comes up in practice with things like:+ // std::vector<uint8_t> v;+ // blake3_hasher_update(&hasher, v.data(), v.size());+ if (input_len == 0) {+ return;+ }++ const uint8_t *input_bytes = (const uint8_t *)input;++ // If we have some partial chunk bytes in the internal chunk_state, we need+ // to finish that chunk first.+ if (chunk_state_len(&self->chunk) > 0) {+ size_t take = BLAKE3_CHUNK_LEN - chunk_state_len(&self->chunk);+ if (take > input_len) {+ take = input_len;+ }+ chunk_state_update(&self->chunk, input_bytes, take);+ input_bytes += take;+ input_len -= take;+ // If we've filled the current chunk and there's more coming, finalize this+ // chunk and proceed. In this case we know it's not the root.+ if (input_len > 0) {+ output_t output = chunk_state_output(&self->chunk);+ uint8_t chunk_cv[32];+ output_chaining_value(&output, chunk_cv);+ hasher_push_cv(self, chunk_cv, self->chunk.chunk_counter);+ chunk_state_reset(&self->chunk, self->key, self->chunk.chunk_counter + 1);+ } else {+ return;+ }+ }++ // Now the chunk_state is clear, and we have more input. If there's more than+ // a single chunk (so, definitely not the root chunk), hash the largest whole+ // subtree we can, with the full benefits of SIMD (and maybe in the future,+ // multi-threading) parallelism. Two restrictions:+ // - The subtree has to be a power-of-2 number of chunks. Only subtrees along+ // the right edge can be incomplete, and we don't know where the right edge+ // is going to be until we get to finalize().+ // - The subtree must evenly divide the total number of chunks up until this+ // point (if total is not 0). If the current incomplete subtree is only+ // waiting for 1 more chunk, we can't hash a subtree of 4 chunks. We have+ // to complete the current subtree first.+ // Because we might need to break up the input to form powers of 2, or to+ // evenly divide what we already have, this part runs in a loop.+ while (input_len > BLAKE3_CHUNK_LEN) {+ size_t subtree_len = round_down_to_power_of_2(input_len);+ uint64_t count_so_far = self->chunk.chunk_counter * BLAKE3_CHUNK_LEN;+ // Shrink the subtree_len until it evenly divides the count so far. We know+ // that subtree_len itself is a power of 2, so we can use a bitmasking+ // trick instead of an actual remainder operation. (Note that if the caller+ // consistently passes power-of-2 inputs of the same size, as is hopefully+ // typical, this loop condition will always fail, and subtree_len will+ // always be the full length of the input.)+ //+ // An aside: We don't have to shrink subtree_len quite this much. For+ // example, if count_so_far is 1, we could pass 2 chunks to+ // compress_subtree_to_parent_node. Since we'll get 2 CVs back, we'll still+ // get the right answer in the end, and we might get to use 2-way SIMD+ // parallelism. The problem with this optimization, is that it gets us+ // stuck always hashing 2 chunks. The total number of chunks will remain+ // odd, and we'll never graduate to higher degrees of parallelism. See+ // https://github.com/BLAKE3-team/BLAKE3/issues/69.+ while ((((uint64_t)(subtree_len - 1)) & count_so_far) != 0) {+ subtree_len /= 2;+ }+ // The shrunken subtree_len might now be 1 chunk long. If so, hash that one+ // chunk by itself. Otherwise, compress the subtree into a pair of CVs.+ uint64_t subtree_chunks = subtree_len / BLAKE3_CHUNK_LEN;+ if (subtree_len <= BLAKE3_CHUNK_LEN) {+ blake3_chunk_state chunk_state;+ chunk_state_init(&chunk_state, self->key, self->chunk.flags);+ chunk_state.chunk_counter = self->chunk.chunk_counter;+ chunk_state_update(&chunk_state, input_bytes, subtree_len);+ output_t output = chunk_state_output(&chunk_state);+ uint8_t cv[BLAKE3_OUT_LEN];+ output_chaining_value(&output, cv);+ hasher_push_cv(self, cv, chunk_state.chunk_counter);+ } else {+ // This is the high-performance happy path, though getting here depends+ // on the caller giving us a long enough input.+ uint8_t cv_pair[2 * BLAKE3_OUT_LEN];+ compress_subtree_to_parent_node(input_bytes, subtree_len, self->key,+ self->chunk.chunk_counter,+ self->chunk.flags, cv_pair, use_tbb);+ hasher_push_cv(self, cv_pair, self->chunk.chunk_counter);+ hasher_push_cv(self, &cv_pair[BLAKE3_OUT_LEN],+ self->chunk.chunk_counter + (subtree_chunks / 2));+ }+ self->chunk.chunk_counter += subtree_chunks;+ input_bytes += subtree_len;+ input_len -= subtree_len;+ }++ // If there's any remaining input less than a full chunk, add it to the chunk+ // state. In that case, also do a final merge loop to make sure the subtree+ // stack doesn't contain any unmerged pairs. The remaining input means we+ // know these merges are non-root. This merge loop isn't strictly necessary+ // here, because hasher_push_chunk_cv already does its own merge loop, but it+ // simplifies blake3_hasher_finalize below.+ if (input_len > 0) {+ chunk_state_update(&self->chunk, input_bytes, input_len);+ hasher_merge_cv_stack(self, self->chunk.chunk_counter);+ }+}++void blake3_hasher_update(blake3_hasher *self, const void *input,+ size_t input_len) {+ bool use_tbb = false;+ blake3_hasher_update_base(self, input, input_len, use_tbb);+}++#if defined(BLAKE3_USE_TBB)+void blake3_hasher_update_tbb(blake3_hasher *self, const void *input,+ size_t input_len) {+ bool use_tbb = true;+ blake3_hasher_update_base(self, input, input_len, use_tbb);+}+#endif // BLAKE3_USE_TBB++void blake3_hasher_finalize(const blake3_hasher *self, uint8_t *out,+ size_t out_len) {+ blake3_hasher_finalize_seek(self, 0, out, out_len);+}++void blake3_hasher_finalize_seek(const blake3_hasher *self, uint64_t seek,+ uint8_t *out, size_t out_len) {+ // Explicitly checking for zero avoids causing UB by passing a null pointer+ // to memcpy. This comes up in practice with things like:+ // std::vector<uint8_t> v;+ // blake3_hasher_finalize(&hasher, v.data(), v.size());+ if (out_len == 0) {+ return;+ }++ // If the subtree stack is empty, then the current chunk is the root.+ if (self->cv_stack_len == 0) {+ output_t output = chunk_state_output(&self->chunk);+ output_root_bytes(&output, seek, out, out_len);+ return;+ }+ // If there are any bytes in the chunk state, finalize that chunk and do a+ // roll-up merge between that chunk hash and every subtree in the stack. In+ // this case, the extra merge loop at the end of blake3_hasher_update+ // guarantees that none of the subtrees in the stack need to be merged with+ // each other first. Otherwise, if there are no bytes in the chunk state,+ // then the top of the stack is a chunk hash, and we start the merge from+ // that.+ output_t output;+ size_t cvs_remaining;+ if (chunk_state_len(&self->chunk) > 0) {+ cvs_remaining = self->cv_stack_len;+ output = chunk_state_output(&self->chunk);+ } else {+ // There are always at least 2 CVs in the stack in this case.+ cvs_remaining = self->cv_stack_len - 2;+ output = parent_output(&self->cv_stack[cvs_remaining * 32], self->key,+ self->chunk.flags);+ }+ while (cvs_remaining > 0) {+ cvs_remaining -= 1;+ uint8_t parent_block[BLAKE3_BLOCK_LEN];+ memcpy(parent_block, &self->cv_stack[cvs_remaining * 32], 32);+ output_chaining_value(&output, &parent_block[32]);+ output = parent_output(parent_block, self->key, self->chunk.flags);+ }+ output_root_bytes(&output, seek, out, out_len);+}++void blake3_hasher_reset(blake3_hasher *self) {+ chunk_state_reset(&self->chunk, self->key, 0);+ self->cv_stack_len = 0;+}--- /dev/null+++ b/veins/src/crypto/blake3/blake3.h@@ -0,0 +1,86 @@+#ifndef BLAKE3_H+#define BLAKE3_H++#include <stddef.h>+#include <stdint.h>++#if !defined(BLAKE3_API)+# if defined(_WIN32) || defined(__CYGWIN__)+# if defined(BLAKE3_DLL)+# if defined(BLAKE3_DLL_EXPORTS)+# define BLAKE3_API __declspec(dllexport)+# else+# define BLAKE3_API __declspec(dllimport)+# endif+# define BLAKE3_PRIVATE+# else+# define BLAKE3_API+# define BLAKE3_PRIVATE+# endif+# elif __GNUC__ >= 4+# define BLAKE3_API __attribute__((visibility("default")))+# define BLAKE3_PRIVATE __attribute__((visibility("hidden")))+# else+# define BLAKE3_API+# define BLAKE3_PRIVATE+# endif+#endif++#ifdef __cplusplus+extern "C" {+#endif++#define BLAKE3_VERSION_STRING "1.8.7"+#define BLAKE3_KEY_LEN 32+#define BLAKE3_OUT_LEN 32+#define BLAKE3_BLOCK_LEN 64+#define BLAKE3_CHUNK_LEN 1024+#define BLAKE3_MAX_DEPTH 54++// This struct is a private implementation detail. It has to be here because+// it's part of the blake3_hasher structure defined below.+typedef struct {+ uint32_t cv[8];+ uint64_t chunk_counter;+ uint8_t buf[BLAKE3_BLOCK_LEN];+ uint8_t buf_len;+ uint8_t blocks_compressed;+ uint8_t flags;+} blake3_chunk_state;++typedef struct {+ uint32_t key[8];+ blake3_chunk_state chunk;+ uint8_t cv_stack_len;+ // The stack size is MAX_DEPTH + 1 because we do lazy merging. For example,+ // with 7 chunks, we have 3 entries in the stack. Adding an 8th chunk+ // requires a 4th entry, rather than merging everything down to 1, because we+ // don't know whether more input is coming. This is different from how the+ // reference implementation does things.+ uint8_t cv_stack[(BLAKE3_MAX_DEPTH + 1) * BLAKE3_OUT_LEN];+} blake3_hasher;++BLAKE3_API const char *blake3_version(void);+BLAKE3_API void blake3_hasher_init(blake3_hasher *self);+BLAKE3_API void blake3_hasher_init_keyed(blake3_hasher *self,+ const uint8_t key[BLAKE3_KEY_LEN]);+BLAKE3_API void blake3_hasher_init_derive_key(blake3_hasher *self, const char *context);+BLAKE3_API void blake3_hasher_init_derive_key_raw(blake3_hasher *self, const void *context,+ size_t context_len);+BLAKE3_API void blake3_hasher_update(blake3_hasher *self, const void *input,+ size_t input_len);+#if defined(BLAKE3_USE_TBB)+BLAKE3_API void blake3_hasher_update_tbb(blake3_hasher *self, const void *input,+ size_t input_len);+#endif // BLAKE3_USE_TBB+BLAKE3_API void blake3_hasher_finalize(const blake3_hasher *self, uint8_t *out,+ size_t out_len);+BLAKE3_API void blake3_hasher_finalize_seek(const blake3_hasher *self, uint64_t seek,+ uint8_t *out, size_t out_len);+BLAKE3_API void blake3_hasher_reset(blake3_hasher *self);++#ifdef __cplusplus+}+#endif++#endif /* BLAKE3_H */--- /dev/null+++ b/veins/src/crypto/blake3/blake3_avx2.c@@ -0,0 +1,326 @@+#include "blake3_impl.h"++#include <immintrin.h>++#define DEGREE 8++INLINE __m256i loadu(const uint8_t src[32]) {+ return _mm256_loadu_si256((const __m256i *)src);+}++INLINE void storeu(__m256i src, uint8_t dest[16]) {+ _mm256_storeu_si256((__m256i *)dest, src);+}++INLINE __m256i addv(__m256i a, __m256i b) { return _mm256_add_epi32(a, b); }++// Note that clang-format doesn't like the name "xor" for some reason.+INLINE __m256i xorv(__m256i a, __m256i b) { return _mm256_xor_si256(a, b); }++INLINE __m256i set1(uint32_t x) { return _mm256_set1_epi32((int32_t)x); }++INLINE __m256i rot16(__m256i x) {+ return _mm256_shuffle_epi8(+ x, _mm256_set_epi8(13, 12, 15, 14, 9, 8, 11, 10, 5, 4, 7, 6, 1, 0, 3, 2,+ 13, 12, 15, 14, 9, 8, 11, 10, 5, 4, 7, 6, 1, 0, 3, 2));+}++INLINE __m256i rot12(__m256i x) {+ return _mm256_or_si256(_mm256_srli_epi32(x, 12), _mm256_slli_epi32(x, 32 - 12));+}++INLINE __m256i rot8(__m256i x) {+ return _mm256_shuffle_epi8(+ x, _mm256_set_epi8(12, 15, 14, 13, 8, 11, 10, 9, 4, 7, 6, 5, 0, 3, 2, 1,+ 12, 15, 14, 13, 8, 11, 10, 9, 4, 7, 6, 5, 0, 3, 2, 1));+}++INLINE __m256i rot7(__m256i x) {+ return _mm256_or_si256(_mm256_srli_epi32(x, 7), _mm256_slli_epi32(x, 32 - 7));+}++INLINE void round_fn(__m256i v[16], __m256i m[16], size_t r) {+ v[0] = addv(v[0], m[(size_t)MSG_SCHEDULE[r][0]]);+ v[1] = addv(v[1], m[(size_t)MSG_SCHEDULE[r][2]]);+ v[2] = addv(v[2], m[(size_t)MSG_SCHEDULE[r][4]]);+ v[3] = addv(v[3], m[(size_t)MSG_SCHEDULE[r][6]]);+ v[0] = addv(v[0], v[4]);+ v[1] = addv(v[1], v[5]);+ v[2] = addv(v[2], v[6]);+ v[3] = addv(v[3], v[7]);+ v[12] = xorv(v[12], v[0]);+ v[13] = xorv(v[13], v[1]);+ v[14] = xorv(v[14], v[2]);+ v[15] = xorv(v[15], v[3]);+ v[12] = rot16(v[12]);+ v[13] = rot16(v[13]);+ v[14] = rot16(v[14]);+ v[15] = rot16(v[15]);+ v[8] = addv(v[8], v[12]);+ v[9] = addv(v[9], v[13]);+ v[10] = addv(v[10], v[14]);+ v[11] = addv(v[11], v[15]);+ v[4] = xorv(v[4], v[8]);+ v[5] = xorv(v[5], v[9]);+ v[6] = xorv(v[6], v[10]);+ v[7] = xorv(v[7], v[11]);+ v[4] = rot12(v[4]);+ v[5] = rot12(v[5]);+ v[6] = rot12(v[6]);+ v[7] = rot12(v[7]);+ v[0] = addv(v[0], m[(size_t)MSG_SCHEDULE[r][1]]);+ v[1] = addv(v[1], m[(size_t)MSG_SCHEDULE[r][3]]);+ v[2] = addv(v[2], m[(size_t)MSG_SCHEDULE[r][5]]);+ v[3] = addv(v[3], m[(size_t)MSG_SCHEDULE[r][7]]);+ v[0] = addv(v[0], v[4]);+ v[1] = addv(v[1], v[5]);+ v[2] = addv(v[2], v[6]);+ v[3] = addv(v[3], v[7]);+ v[12] = xorv(v[12], v[0]);+ v[13] = xorv(v[13], v[1]);+ v[14] = xorv(v[14], v[2]);+ v[15] = xorv(v[15], v[3]);+ v[12] = rot8(v[12]);+ v[13] = rot8(v[13]);+ v[14] = rot8(v[14]);+ v[15] = rot8(v[15]);+ v[8] = addv(v[8], v[12]);+ v[9] = addv(v[9], v[13]);+ v[10] = addv(v[10], v[14]);+ v[11] = addv(v[11], v[15]);+ v[4] = xorv(v[4], v[8]);+ v[5] = xorv(v[5], v[9]);+ v[6] = xorv(v[6], v[10]);+ v[7] = xorv(v[7], v[11]);+ v[4] = rot7(v[4]);+ v[5] = rot7(v[5]);+ v[6] = rot7(v[6]);+ v[7] = rot7(v[7]);++ v[0] = addv(v[0], m[(size_t)MSG_SCHEDULE[r][8]]);+ v[1] = addv(v[1], m[(size_t)MSG_SCHEDULE[r][10]]);+ v[2] = addv(v[2], m[(size_t)MSG_SCHEDULE[r][12]]);+ v[3] = addv(v[3], m[(size_t)MSG_SCHEDULE[r][14]]);+ v[0] = addv(v[0], v[5]);+ v[1] = addv(v[1], v[6]);+ v[2] = addv(v[2], v[7]);+ v[3] = addv(v[3], v[4]);+ v[15] = xorv(v[15], v[0]);+ v[12] = xorv(v[12], v[1]);+ v[13] = xorv(v[13], v[2]);+ v[14] = xorv(v[14], v[3]);+ v[15] = rot16(v[15]);+ v[12] = rot16(v[12]);+ v[13] = rot16(v[13]);+ v[14] = rot16(v[14]);+ v[10] = addv(v[10], v[15]);+ v[11] = addv(v[11], v[12]);+ v[8] = addv(v[8], v[13]);+ v[9] = addv(v[9], v[14]);+ v[5] = xorv(v[5], v[10]);+ v[6] = xorv(v[6], v[11]);+ v[7] = xorv(v[7], v[8]);+ v[4] = xorv(v[4], v[9]);+ v[5] = rot12(v[5]);+ v[6] = rot12(v[6]);+ v[7] = rot12(v[7]);+ v[4] = rot12(v[4]);+ v[0] = addv(v[0], m[(size_t)MSG_SCHEDULE[r][9]]);+ v[1] = addv(v[1], m[(size_t)MSG_SCHEDULE[r][11]]);+ v[2] = addv(v[2], m[(size_t)MSG_SCHEDULE[r][13]]);+ v[3] = addv(v[3], m[(size_t)MSG_SCHEDULE[r][15]]);+ v[0] = addv(v[0], v[5]);+ v[1] = addv(v[1], v[6]);+ v[2] = addv(v[2], v[7]);+ v[3] = addv(v[3], v[4]);+ v[15] = xorv(v[15], v[0]);+ v[12] = xorv(v[12], v[1]);+ v[13] = xorv(v[13], v[2]);+ v[14] = xorv(v[14], v[3]);+ v[15] = rot8(v[15]);+ v[12] = rot8(v[12]);+ v[13] = rot8(v[13]);+ v[14] = rot8(v[14]);+ v[10] = addv(v[10], v[15]);+ v[11] = addv(v[11], v[12]);+ v[8] = addv(v[8], v[13]);+ v[9] = addv(v[9], v[14]);+ v[5] = xorv(v[5], v[10]);+ v[6] = xorv(v[6], v[11]);+ v[7] = xorv(v[7], v[8]);+ v[4] = xorv(v[4], v[9]);+ v[5] = rot7(v[5]);+ v[6] = rot7(v[6]);+ v[7] = rot7(v[7]);+ v[4] = rot7(v[4]);+}++INLINE void transpose_vecs(__m256i vecs[DEGREE]) {+ // Interleave 32-bit lanes. The low unpack is lanes 00/11/44/55, and the high+ // is 22/33/66/77.+ __m256i ab_0145 = _mm256_unpacklo_epi32(vecs[0], vecs[1]);+ __m256i ab_2367 = _mm256_unpackhi_epi32(vecs[0], vecs[1]);+ __m256i cd_0145 = _mm256_unpacklo_epi32(vecs[2], vecs[3]);+ __m256i cd_2367 = _mm256_unpackhi_epi32(vecs[2], vecs[3]);+ __m256i ef_0145 = _mm256_unpacklo_epi32(vecs[4], vecs[5]);+ __m256i ef_2367 = _mm256_unpackhi_epi32(vecs[4], vecs[5]);+ __m256i gh_0145 = _mm256_unpacklo_epi32(vecs[6], vecs[7]);+ __m256i gh_2367 = _mm256_unpackhi_epi32(vecs[6], vecs[7]);++ // Interleave 64-bit lanes. The low unpack is lanes 00/22 and the high is+ // 11/33.+ __m256i abcd_04 = _mm256_unpacklo_epi64(ab_0145, cd_0145);+ __m256i abcd_15 = _mm256_unpackhi_epi64(ab_0145, cd_0145);+ __m256i abcd_26 = _mm256_unpacklo_epi64(ab_2367, cd_2367);+ __m256i abcd_37 = _mm256_unpackhi_epi64(ab_2367, cd_2367);+ __m256i efgh_04 = _mm256_unpacklo_epi64(ef_0145, gh_0145);+ __m256i efgh_15 = _mm256_unpackhi_epi64(ef_0145, gh_0145);+ __m256i efgh_26 = _mm256_unpacklo_epi64(ef_2367, gh_2367);+ __m256i efgh_37 = _mm256_unpackhi_epi64(ef_2367, gh_2367);++ // Interleave 128-bit lanes.+ vecs[0] = _mm256_permute2x128_si256(abcd_04, efgh_04, 0x20);+ vecs[1] = _mm256_permute2x128_si256(abcd_15, efgh_15, 0x20);+ vecs[2] = _mm256_permute2x128_si256(abcd_26, efgh_26, 0x20);+ vecs[3] = _mm256_permute2x128_si256(abcd_37, efgh_37, 0x20);+ vecs[4] = _mm256_permute2x128_si256(abcd_04, efgh_04, 0x31);+ vecs[5] = _mm256_permute2x128_si256(abcd_15, efgh_15, 0x31);+ vecs[6] = _mm256_permute2x128_si256(abcd_26, efgh_26, 0x31);+ vecs[7] = _mm256_permute2x128_si256(abcd_37, efgh_37, 0x31);+}++INLINE void transpose_msg_vecs(const uint8_t *const *inputs,+ size_t block_offset, __m256i out[16]) {+ out[0] = loadu(&inputs[0][block_offset + 0 * sizeof(__m256i)]);+ out[1] = loadu(&inputs[1][block_offset + 0 * sizeof(__m256i)]);+ out[2] = loadu(&inputs[2][block_offset + 0 * sizeof(__m256i)]);+ out[3] = loadu(&inputs[3][block_offset + 0 * sizeof(__m256i)]);+ out[4] = loadu(&inputs[4][block_offset + 0 * sizeof(__m256i)]);+ out[5] = loadu(&inputs[5][block_offset + 0 * sizeof(__m256i)]);+ out[6] = loadu(&inputs[6][block_offset + 0 * sizeof(__m256i)]);+ out[7] = loadu(&inputs[7][block_offset + 0 * sizeof(__m256i)]);+ out[8] = loadu(&inputs[0][block_offset + 1 * sizeof(__m256i)]);+ out[9] = loadu(&inputs[1][block_offset + 1 * sizeof(__m256i)]);+ out[10] = loadu(&inputs[2][block_offset + 1 * sizeof(__m256i)]);+ out[11] = loadu(&inputs[3][block_offset + 1 * sizeof(__m256i)]);+ out[12] = loadu(&inputs[4][block_offset + 1 * sizeof(__m256i)]);+ out[13] = loadu(&inputs[5][block_offset + 1 * sizeof(__m256i)]);+ out[14] = loadu(&inputs[6][block_offset + 1 * sizeof(__m256i)]);+ out[15] = loadu(&inputs[7][block_offset + 1 * sizeof(__m256i)]);+ for (size_t i = 0; i < 8; ++i) {+ _mm_prefetch((const void *)&inputs[i][block_offset + 256], _MM_HINT_T0);+ }+ transpose_vecs(&out[0]);+ transpose_vecs(&out[8]);+}++INLINE void load_counters(uint64_t counter, bool increment_counter,+ __m256i *out_lo, __m256i *out_hi) {+ const __m256i mask = _mm256_set1_epi32(-(int32_t)increment_counter);+ const __m256i add0 = _mm256_set_epi32(7, 6, 5, 4, 3, 2, 1, 0);+ const __m256i add1 = _mm256_and_si256(mask, add0);+ __m256i l = _mm256_add_epi32(_mm256_set1_epi32((int32_t)counter), add1);+ __m256i carry = _mm256_cmpgt_epi32(_mm256_xor_si256(add1, _mm256_set1_epi32(0x80000000)), + _mm256_xor_si256( l, _mm256_set1_epi32(0x80000000)));+ __m256i h = _mm256_sub_epi32(_mm256_set1_epi32((int32_t)(counter >> 32)), carry);+ *out_lo = l;+ *out_hi = h;+}++static+void blake3_hash8_avx2(const uint8_t *const *inputs, size_t blocks,+ const uint32_t key[8], uint64_t counter,+ bool increment_counter, uint8_t flags,+ uint8_t flags_start, uint8_t flags_end, uint8_t *out) {+ __m256i h_vecs[8] = {+ set1(key[0]), set1(key[1]), set1(key[2]), set1(key[3]),+ set1(key[4]), set1(key[5]), set1(key[6]), set1(key[7]),+ };+ __m256i counter_low_vec, counter_high_vec;+ load_counters(counter, increment_counter, &counter_low_vec,+ &counter_high_vec);+ uint8_t block_flags = flags | flags_start;++ for (size_t block = 0; block < blocks; block++) {+ if (block + 1 == blocks) {+ block_flags |= flags_end;+ }+ __m256i block_len_vec = set1(BLAKE3_BLOCK_LEN);+ __m256i block_flags_vec = set1(block_flags);+ __m256i msg_vecs[16];+ transpose_msg_vecs(inputs, block * BLAKE3_BLOCK_LEN, msg_vecs);++ __m256i v[16] = {+ h_vecs[0], h_vecs[1], h_vecs[2], h_vecs[3],+ h_vecs[4], h_vecs[5], h_vecs[6], h_vecs[7],+ set1(IV[0]), set1(IV[1]), set1(IV[2]), set1(IV[3]),+ counter_low_vec, counter_high_vec, block_len_vec, block_flags_vec,+ };+ round_fn(v, msg_vecs, 0);+ round_fn(v, msg_vecs, 1);+ round_fn(v, msg_vecs, 2);+ round_fn(v, msg_vecs, 3);+ round_fn(v, msg_vecs, 4);+ round_fn(v, msg_vecs, 5);+ round_fn(v, msg_vecs, 6);+ h_vecs[0] = xorv(v[0], v[8]);+ h_vecs[1] = xorv(v[1], v[9]);+ h_vecs[2] = xorv(v[2], v[10]);+ h_vecs[3] = xorv(v[3], v[11]);+ h_vecs[4] = xorv(v[4], v[12]);+ h_vecs[5] = xorv(v[5], v[13]);+ h_vecs[6] = xorv(v[6], v[14]);+ h_vecs[7] = xorv(v[7], v[15]);++ block_flags = flags;+ }++ transpose_vecs(h_vecs);+ storeu(h_vecs[0], &out[0 * sizeof(__m256i)]);+ storeu(h_vecs[1], &out[1 * sizeof(__m256i)]);+ storeu(h_vecs[2], &out[2 * sizeof(__m256i)]);+ storeu(h_vecs[3], &out[3 * sizeof(__m256i)]);+ storeu(h_vecs[4], &out[4 * sizeof(__m256i)]);+ storeu(h_vecs[5], &out[5 * sizeof(__m256i)]);+ storeu(h_vecs[6], &out[6 * sizeof(__m256i)]);+ storeu(h_vecs[7], &out[7 * sizeof(__m256i)]);+}++#if !defined(BLAKE3_NO_SSE41)+void blake3_hash_many_sse41(const uint8_t *const *inputs, size_t num_inputs,+ size_t blocks, const uint32_t key[8],+ uint64_t counter, bool increment_counter,+ uint8_t flags, uint8_t flags_start,+ uint8_t flags_end, uint8_t *out);+#else+void blake3_hash_many_portable(const uint8_t *const *inputs, size_t num_inputs,+ size_t blocks, const uint32_t key[8],+ uint64_t counter, bool increment_counter,+ uint8_t flags, uint8_t flags_start,+ uint8_t flags_end, uint8_t *out);+#endif++void blake3_hash_many_avx2(const uint8_t *const *inputs, size_t num_inputs,+ size_t blocks, const uint32_t key[8],+ uint64_t counter, bool increment_counter,+ uint8_t flags, uint8_t flags_start,+ uint8_t flags_end, uint8_t *out) {+ while (num_inputs >= DEGREE) {+ blake3_hash8_avx2(inputs, blocks, key, counter, increment_counter, flags,+ flags_start, flags_end, out);+ if (increment_counter) {+ counter += DEGREE;+ }+ inputs += DEGREE;+ num_inputs -= DEGREE;+ out = &out[DEGREE * BLAKE3_OUT_LEN];+ }+#if !defined(BLAKE3_NO_SSE41)+ blake3_hash_many_sse41(inputs, num_inputs, blocks, key, counter,+ increment_counter, flags, flags_start, flags_end, out);+#else+ blake3_hash_many_portable(inputs, num_inputs, blocks, key, counter,+ increment_counter, flags, flags_start, flags_end,+ out);+#endif+}--- /dev/null+++ b/veins/src/crypto/blake3/blake3_avx512.c@@ -0,0 +1,1388 @@+#include "blake3_impl.h"++#include <immintrin.h>++#define _mm_shuffle_ps2(a, b, c) \+ (_mm_castps_si128( \+ _mm_shuffle_ps(_mm_castsi128_ps(a), _mm_castsi128_ps(b), (c))))++INLINE __m128i loadu_128(const uint8_t src[16]) {+ return _mm_loadu_si128((void*)src);+}++INLINE __m256i loadu_256(const uint8_t src[32]) {+ return _mm256_loadu_si256((void*)src);+}++INLINE __m512i loadu_512(const uint8_t src[64]) {+ return _mm512_loadu_si512((void*)src);+}++INLINE void storeu_128(__m128i src, uint8_t dest[16]) {+ _mm_storeu_si128((void*)dest, src);+}++INLINE void storeu_256(__m256i src, uint8_t dest[16]) {+ _mm256_storeu_si256((void*)dest, src);+}++INLINE void storeu_512(__m512i src, uint8_t dest[16]) {+ _mm512_storeu_si512((void*)dest, src);+}++INLINE __m128i add_128(__m128i a, __m128i b) { return _mm_add_epi32(a, b); }++INLINE __m256i add_256(__m256i a, __m256i b) { return _mm256_add_epi32(a, b); }++INLINE __m512i add_512(__m512i a, __m512i b) { return _mm512_add_epi32(a, b); }++INLINE __m128i xor_128(__m128i a, __m128i b) { return _mm_xor_si128(a, b); }++INLINE __m256i xor_256(__m256i a, __m256i b) { return _mm256_xor_si256(a, b); }++INLINE __m512i xor_512(__m512i a, __m512i b) { return _mm512_xor_si512(a, b); }++INLINE __m128i set1_128(uint32_t x) { return _mm_set1_epi32((int32_t)x); }++INLINE __m256i set1_256(uint32_t x) { return _mm256_set1_epi32((int32_t)x); }++INLINE __m512i set1_512(uint32_t x) { return _mm512_set1_epi32((int32_t)x); }++INLINE __m128i set4(uint32_t a, uint32_t b, uint32_t c, uint32_t d) {+ return _mm_setr_epi32((int32_t)a, (int32_t)b, (int32_t)c, (int32_t)d);+}++INLINE __m128i rot16_128(__m128i x) { return _mm_ror_epi32(x, 16); }++INLINE __m256i rot16_256(__m256i x) { return _mm256_ror_epi32(x, 16); }++INLINE __m512i rot16_512(__m512i x) { return _mm512_ror_epi32(x, 16); }++INLINE __m128i rot12_128(__m128i x) { return _mm_ror_epi32(x, 12); }++INLINE __m256i rot12_256(__m256i x) { return _mm256_ror_epi32(x, 12); }++INLINE __m512i rot12_512(__m512i x) { return _mm512_ror_epi32(x, 12); }++INLINE __m128i rot8_128(__m128i x) { return _mm_ror_epi32(x, 8); }++INLINE __m256i rot8_256(__m256i x) { return _mm256_ror_epi32(x, 8); }++INLINE __m512i rot8_512(__m512i x) { return _mm512_ror_epi32(x, 8); }++INLINE __m128i rot7_128(__m128i x) { return _mm_ror_epi32(x, 7); }++INLINE __m256i rot7_256(__m256i x) { return _mm256_ror_epi32(x, 7); }++INLINE __m512i rot7_512(__m512i x) { return _mm512_ror_epi32(x, 7); }++/*+ * ----------------------------------------------------------------------------+ * compress_avx512+ * ----------------------------------------------------------------------------+ */++INLINE void g1(__m128i *row0, __m128i *row1, __m128i *row2, __m128i *row3,+ __m128i m) {+ *row0 = add_128(add_128(*row0, m), *row1);+ *row3 = xor_128(*row3, *row0);+ *row3 = rot16_128(*row3);+ *row2 = add_128(*row2, *row3);+ *row1 = xor_128(*row1, *row2);+ *row1 = rot12_128(*row1);+}++INLINE void g2(__m128i *row0, __m128i *row1, __m128i *row2, __m128i *row3,+ __m128i m) {+ *row0 = add_128(add_128(*row0, m), *row1);+ *row3 = xor_128(*row3, *row0);+ *row3 = rot8_128(*row3);+ *row2 = add_128(*row2, *row3);+ *row1 = xor_128(*row1, *row2);+ *row1 = rot7_128(*row1);+}++// Note the optimization here of leaving row1 as the unrotated row, rather than+// row0. All the message loads below are adjusted to compensate for this. See+// discussion at https://github.com/sneves/blake2-avx2/pull/4+INLINE void diagonalize(__m128i *row0, __m128i *row2, __m128i *row3) {+ *row0 = _mm_shuffle_epi32(*row0, _MM_SHUFFLE(2, 1, 0, 3));+ *row3 = _mm_shuffle_epi32(*row3, _MM_SHUFFLE(1, 0, 3, 2));+ *row2 = _mm_shuffle_epi32(*row2, _MM_SHUFFLE(0, 3, 2, 1));+}++INLINE void undiagonalize(__m128i *row0, __m128i *row2, __m128i *row3) {+ *row0 = _mm_shuffle_epi32(*row0, _MM_SHUFFLE(0, 3, 2, 1));+ *row3 = _mm_shuffle_epi32(*row3, _MM_SHUFFLE(1, 0, 3, 2));+ *row2 = _mm_shuffle_epi32(*row2, _MM_SHUFFLE(2, 1, 0, 3));+}++INLINE void compress_pre(__m128i rows[4], const uint32_t cv[8],+ const uint8_t block[BLAKE3_BLOCK_LEN],+ uint8_t block_len, uint64_t counter, uint8_t flags) {+ rows[0] = loadu_128((uint8_t *)&cv[0]);+ rows[1] = loadu_128((uint8_t *)&cv[4]);+ rows[2] = set4(IV[0], IV[1], IV[2], IV[3]);+ rows[3] = set4(counter_low(counter), counter_high(counter),+ (uint32_t)block_len, (uint32_t)flags);++ __m128i m0 = loadu_128(&block[sizeof(__m128i) * 0]);+ __m128i m1 = loadu_128(&block[sizeof(__m128i) * 1]);+ __m128i m2 = loadu_128(&block[sizeof(__m128i) * 2]);+ __m128i m3 = loadu_128(&block[sizeof(__m128i) * 3]);++ __m128i t0, t1, t2, t3, tt;++ // Round 1. The first round permutes the message words from the original+ // input order, into the groups that get mixed in parallel.+ t0 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(2, 0, 2, 0)); // 6 4 2 0+ g1(&rows[0], &rows[1], &rows[2], &rows[3], t0);+ t1 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(3, 1, 3, 1)); // 7 5 3 1+ g2(&rows[0], &rows[1], &rows[2], &rows[3], t1);+ diagonalize(&rows[0], &rows[2], &rows[3]);+ t2 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(2, 0, 2, 0)); // 14 12 10 8+ t2 = _mm_shuffle_epi32(t2, _MM_SHUFFLE(2, 1, 0, 3)); // 12 10 8 14+ g1(&rows[0], &rows[1], &rows[2], &rows[3], t2);+ t3 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(3, 1, 3, 1)); // 15 13 11 9+ t3 = _mm_shuffle_epi32(t3, _MM_SHUFFLE(2, 1, 0, 3)); // 13 11 9 15+ g2(&rows[0], &rows[1], &rows[2], &rows[3], t3);+ undiagonalize(&rows[0], &rows[2], &rows[3]);+ m0 = t0;+ m1 = t1;+ m2 = t2;+ m3 = t3;++ // Round 2. This round and all following rounds apply a fixed permutation+ // to the message words from the round before.+ t0 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(3, 1, 1, 2));+ t0 = _mm_shuffle_epi32(t0, _MM_SHUFFLE(0, 3, 2, 1));+ g1(&rows[0], &rows[1], &rows[2], &rows[3], t0);+ t1 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(3, 3, 2, 2));+ tt = _mm_shuffle_epi32(m0, _MM_SHUFFLE(0, 0, 3, 3));+ t1 = _mm_blend_epi16(tt, t1, 0xCC);+ g2(&rows[0], &rows[1], &rows[2], &rows[3], t1);+ diagonalize(&rows[0], &rows[2], &rows[3]);+ t2 = _mm_unpacklo_epi64(m3, m1);+ tt = _mm_blend_epi16(t2, m2, 0xC0);+ t2 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(1, 3, 2, 0));+ g1(&rows[0], &rows[1], &rows[2], &rows[3], t2);+ t3 = _mm_unpackhi_epi32(m1, m3);+ tt = _mm_unpacklo_epi32(m2, t3);+ t3 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(0, 1, 3, 2));+ g2(&rows[0], &rows[1], &rows[2], &rows[3], t3);+ undiagonalize(&rows[0], &rows[2], &rows[3]);+ m0 = t0;+ m1 = t1;+ m2 = t2;+ m3 = t3;++ // Round 3+ t0 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(3, 1, 1, 2));+ t0 = _mm_shuffle_epi32(t0, _MM_SHUFFLE(0, 3, 2, 1));+ g1(&rows[0], &rows[1], &rows[2], &rows[3], t0);+ t1 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(3, 3, 2, 2));+ tt = _mm_shuffle_epi32(m0, _MM_SHUFFLE(0, 0, 3, 3));+ t1 = _mm_blend_epi16(tt, t1, 0xCC);+ g2(&rows[0], &rows[1], &rows[2], &rows[3], t1);+ diagonalize(&rows[0], &rows[2], &rows[3]);+ t2 = _mm_unpacklo_epi64(m3, m1);+ tt = _mm_blend_epi16(t2, m2, 0xC0);+ t2 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(1, 3, 2, 0));+ g1(&rows[0], &rows[1], &rows[2], &rows[3], t2);+ t3 = _mm_unpackhi_epi32(m1, m3);+ tt = _mm_unpacklo_epi32(m2, t3);+ t3 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(0, 1, 3, 2));+ g2(&rows[0], &rows[1], &rows[2], &rows[3], t3);+ undiagonalize(&rows[0], &rows[2], &rows[3]);+ m0 = t0;+ m1 = t1;+ m2 = t2;+ m3 = t3;++ // Round 4+ t0 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(3, 1, 1, 2));+ t0 = _mm_shuffle_epi32(t0, _MM_SHUFFLE(0, 3, 2, 1));+ g1(&rows[0], &rows[1], &rows[2], &rows[3], t0);+ t1 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(3, 3, 2, 2));+ tt = _mm_shuffle_epi32(m0, _MM_SHUFFLE(0, 0, 3, 3));+ t1 = _mm_blend_epi16(tt, t1, 0xCC);+ g2(&rows[0], &rows[1], &rows[2], &rows[3], t1);+ diagonalize(&rows[0], &rows[2], &rows[3]);+ t2 = _mm_unpacklo_epi64(m3, m1);+ tt = _mm_blend_epi16(t2, m2, 0xC0);+ t2 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(1, 3, 2, 0));+ g1(&rows[0], &rows[1], &rows[2], &rows[3], t2);+ t3 = _mm_unpackhi_epi32(m1, m3);+ tt = _mm_unpacklo_epi32(m2, t3);+ t3 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(0, 1, 3, 2));+ g2(&rows[0], &rows[1], &rows[2], &rows[3], t3);+ undiagonalize(&rows[0], &rows[2], &rows[3]);+ m0 = t0;+ m1 = t1;+ m2 = t2;+ m3 = t3;++ // Round 5+ t0 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(3, 1, 1, 2));+ t0 = _mm_shuffle_epi32(t0, _MM_SHUFFLE(0, 3, 2, 1));+ g1(&rows[0], &rows[1], &rows[2], &rows[3], t0);+ t1 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(3, 3, 2, 2));+ tt = _mm_shuffle_epi32(m0, _MM_SHUFFLE(0, 0, 3, 3));+ t1 = _mm_blend_epi16(tt, t1, 0xCC);+ g2(&rows[0], &rows[1], &rows[2], &rows[3], t1);+ diagonalize(&rows[0], &rows[2], &rows[3]);+ t2 = _mm_unpacklo_epi64(m3, m1);+ tt = _mm_blend_epi16(t2, m2, 0xC0);+ t2 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(1, 3, 2, 0));+ g1(&rows[0], &rows[1], &rows[2], &rows[3], t2);+ t3 = _mm_unpackhi_epi32(m1, m3);+ tt = _mm_unpacklo_epi32(m2, t3);+ t3 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(0, 1, 3, 2));+ g2(&rows[0], &rows[1], &rows[2], &rows[3], t3);+ undiagonalize(&rows[0], &rows[2], &rows[3]);+ m0 = t0;+ m1 = t1;+ m2 = t2;+ m3 = t3;++ // Round 6+ t0 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(3, 1, 1, 2));+ t0 = _mm_shuffle_epi32(t0, _MM_SHUFFLE(0, 3, 2, 1));+ g1(&rows[0], &rows[1], &rows[2], &rows[3], t0);+ t1 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(3, 3, 2, 2));+ tt = _mm_shuffle_epi32(m0, _MM_SHUFFLE(0, 0, 3, 3));+ t1 = _mm_blend_epi16(tt, t1, 0xCC);+ g2(&rows[0], &rows[1], &rows[2], &rows[3], t1);+ diagonalize(&rows[0], &rows[2], &rows[3]);+ t2 = _mm_unpacklo_epi64(m3, m1);+ tt = _mm_blend_epi16(t2, m2, 0xC0);+ t2 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(1, 3, 2, 0));+ g1(&rows[0], &rows[1], &rows[2], &rows[3], t2);+ t3 = _mm_unpackhi_epi32(m1, m3);+ tt = _mm_unpacklo_epi32(m2, t3);+ t3 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(0, 1, 3, 2));+ g2(&rows[0], &rows[1], &rows[2], &rows[3], t3);+ undiagonalize(&rows[0], &rows[2], &rows[3]);+ m0 = t0;+ m1 = t1;+ m2 = t2;+ m3 = t3;++ // Round 7+ t0 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(3, 1, 1, 2));+ t0 = _mm_shuffle_epi32(t0, _MM_SHUFFLE(0, 3, 2, 1));+ g1(&rows[0], &rows[1], &rows[2], &rows[3], t0);+ t1 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(3, 3, 2, 2));+ tt = _mm_shuffle_epi32(m0, _MM_SHUFFLE(0, 0, 3, 3));+ t1 = _mm_blend_epi16(tt, t1, 0xCC);+ g2(&rows[0], &rows[1], &rows[2], &rows[3], t1);+ diagonalize(&rows[0], &rows[2], &rows[3]);+ t2 = _mm_unpacklo_epi64(m3, m1);+ tt = _mm_blend_epi16(t2, m2, 0xC0);+ t2 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(1, 3, 2, 0));+ g1(&rows[0], &rows[1], &rows[2], &rows[3], t2);+ t3 = _mm_unpackhi_epi32(m1, m3);+ tt = _mm_unpacklo_epi32(m2, t3);+ t3 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(0, 1, 3, 2));+ g2(&rows[0], &rows[1], &rows[2], &rows[3], t3);+ undiagonalize(&rows[0], &rows[2], &rows[3]);+}++void blake3_compress_xof_avx512(const uint32_t cv[8],+ const uint8_t block[BLAKE3_BLOCK_LEN],+ uint8_t block_len, uint64_t counter,+ uint8_t flags, uint8_t out[64]) {+ __m128i rows[4];+ compress_pre(rows, cv, block, block_len, counter, flags);+ storeu_128(xor_128(rows[0], rows[2]), &out[0]);+ storeu_128(xor_128(rows[1], rows[3]), &out[16]);+ storeu_128(xor_128(rows[2], loadu_128((uint8_t *)&cv[0])), &out[32]);+ storeu_128(xor_128(rows[3], loadu_128((uint8_t *)&cv[4])), &out[48]);+}++void blake3_compress_in_place_avx512(uint32_t cv[8],+ const uint8_t block[BLAKE3_BLOCK_LEN],+ uint8_t block_len, uint64_t counter,+ uint8_t flags) {+ __m128i rows[4];+ compress_pre(rows, cv, block, block_len, counter, flags);+ storeu_128(xor_128(rows[0], rows[2]), (uint8_t *)&cv[0]);+ storeu_128(xor_128(rows[1], rows[3]), (uint8_t *)&cv[4]);+}++/*+ * ----------------------------------------------------------------------------+ * hash4_avx512+ * ----------------------------------------------------------------------------+ */++INLINE void round_fn4(__m128i v[16], __m128i m[16], size_t r) {+ v[0] = add_128(v[0], m[(size_t)MSG_SCHEDULE[r][0]]);+ v[1] = add_128(v[1], m[(size_t)MSG_SCHEDULE[r][2]]);+ v[2] = add_128(v[2], m[(size_t)MSG_SCHEDULE[r][4]]);+ v[3] = add_128(v[3], m[(size_t)MSG_SCHEDULE[r][6]]);+ v[0] = add_128(v[0], v[4]);+ v[1] = add_128(v[1], v[5]);+ v[2] = add_128(v[2], v[6]);+ v[3] = add_128(v[3], v[7]);+ v[12] = xor_128(v[12], v[0]);+ v[13] = xor_128(v[13], v[1]);+ v[14] = xor_128(v[14], v[2]);+ v[15] = xor_128(v[15], v[3]);+ v[12] = rot16_128(v[12]);+ v[13] = rot16_128(v[13]);+ v[14] = rot16_128(v[14]);+ v[15] = rot16_128(v[15]);+ v[8] = add_128(v[8], v[12]);+ v[9] = add_128(v[9], v[13]);+ v[10] = add_128(v[10], v[14]);+ v[11] = add_128(v[11], v[15]);+ v[4] = xor_128(v[4], v[8]);+ v[5] = xor_128(v[5], v[9]);+ v[6] = xor_128(v[6], v[10]);+ v[7] = xor_128(v[7], v[11]);+ v[4] = rot12_128(v[4]);+ v[5] = rot12_128(v[5]);+ v[6] = rot12_128(v[6]);+ v[7] = rot12_128(v[7]);+ v[0] = add_128(v[0], m[(size_t)MSG_SCHEDULE[r][1]]);+ v[1] = add_128(v[1], m[(size_t)MSG_SCHEDULE[r][3]]);+ v[2] = add_128(v[2], m[(size_t)MSG_SCHEDULE[r][5]]);+ v[3] = add_128(v[3], m[(size_t)MSG_SCHEDULE[r][7]]);+ v[0] = add_128(v[0], v[4]);+ v[1] = add_128(v[1], v[5]);+ v[2] = add_128(v[2], v[6]);+ v[3] = add_128(v[3], v[7]);+ v[12] = xor_128(v[12], v[0]);+ v[13] = xor_128(v[13], v[1]);+ v[14] = xor_128(v[14], v[2]);+ v[15] = xor_128(v[15], v[3]);+ v[12] = rot8_128(v[12]);+ v[13] = rot8_128(v[13]);+ v[14] = rot8_128(v[14]);+ v[15] = rot8_128(v[15]);+ v[8] = add_128(v[8], v[12]);+ v[9] = add_128(v[9], v[13]);+ v[10] = add_128(v[10], v[14]);+ v[11] = add_128(v[11], v[15]);+ v[4] = xor_128(v[4], v[8]);+ v[5] = xor_128(v[5], v[9]);+ v[6] = xor_128(v[6], v[10]);+ v[7] = xor_128(v[7], v[11]);+ v[4] = rot7_128(v[4]);+ v[5] = rot7_128(v[5]);+ v[6] = rot7_128(v[6]);+ v[7] = rot7_128(v[7]);++ v[0] = add_128(v[0], m[(size_t)MSG_SCHEDULE[r][8]]);+ v[1] = add_128(v[1], m[(size_t)MSG_SCHEDULE[r][10]]);+ v[2] = add_128(v[2], m[(size_t)MSG_SCHEDULE[r][12]]);+ v[3] = add_128(v[3], m[(size_t)MSG_SCHEDULE[r][14]]);+ v[0] = add_128(v[0], v[5]);+ v[1] = add_128(v[1], v[6]);+ v[2] = add_128(v[2], v[7]);+ v[3] = add_128(v[3], v[4]);+ v[15] = xor_128(v[15], v[0]);+ v[12] = xor_128(v[12], v[1]);+ v[13] = xor_128(v[13], v[2]);+ v[14] = xor_128(v[14], v[3]);+ v[15] = rot16_128(v[15]);+ v[12] = rot16_128(v[12]);+ v[13] = rot16_128(v[13]);+ v[14] = rot16_128(v[14]);+ v[10] = add_128(v[10], v[15]);+ v[11] = add_128(v[11], v[12]);+ v[8] = add_128(v[8], v[13]);+ v[9] = add_128(v[9], v[14]);+ v[5] = xor_128(v[5], v[10]);+ v[6] = xor_128(v[6], v[11]);+ v[7] = xor_128(v[7], v[8]);+ v[4] = xor_128(v[4], v[9]);+ v[5] = rot12_128(v[5]);+ v[6] = rot12_128(v[6]);+ v[7] = rot12_128(v[7]);+ v[4] = rot12_128(v[4]);+ v[0] = add_128(v[0], m[(size_t)MSG_SCHEDULE[r][9]]);+ v[1] = add_128(v[1], m[(size_t)MSG_SCHEDULE[r][11]]);+ v[2] = add_128(v[2], m[(size_t)MSG_SCHEDULE[r][13]]);+ v[3] = add_128(v[3], m[(size_t)MSG_SCHEDULE[r][15]]);+ v[0] = add_128(v[0], v[5]);+ v[1] = add_128(v[1], v[6]);+ v[2] = add_128(v[2], v[7]);+ v[3] = add_128(v[3], v[4]);+ v[15] = xor_128(v[15], v[0]);+ v[12] = xor_128(v[12], v[1]);+ v[13] = xor_128(v[13], v[2]);+ v[14] = xor_128(v[14], v[3]);+ v[15] = rot8_128(v[15]);+ v[12] = rot8_128(v[12]);+ v[13] = rot8_128(v[13]);+ v[14] = rot8_128(v[14]);+ v[10] = add_128(v[10], v[15]);+ v[11] = add_128(v[11], v[12]);+ v[8] = add_128(v[8], v[13]);+ v[9] = add_128(v[9], v[14]);+ v[5] = xor_128(v[5], v[10]);+ v[6] = xor_128(v[6], v[11]);+ v[7] = xor_128(v[7], v[8]);+ v[4] = xor_128(v[4], v[9]);+ v[5] = rot7_128(v[5]);+ v[6] = rot7_128(v[6]);+ v[7] = rot7_128(v[7]);+ v[4] = rot7_128(v[4]);+}++INLINE void transpose_vecs_128(__m128i vecs[4]) {+ // Interleave 32-bit lanes. The low unpack is lanes 00/11 and the high is+ // 22/33. Note that this doesn't split the vector into two lanes, as the+ // AVX2 counterparts do.+ __m128i ab_01 = _mm_unpacklo_epi32(vecs[0], vecs[1]);+ __m128i ab_23 = _mm_unpackhi_epi32(vecs[0], vecs[1]);+ __m128i cd_01 = _mm_unpacklo_epi32(vecs[2], vecs[3]);+ __m128i cd_23 = _mm_unpackhi_epi32(vecs[2], vecs[3]);++ // Interleave 64-bit lanes.+ __m128i abcd_0 = _mm_unpacklo_epi64(ab_01, cd_01);+ __m128i abcd_1 = _mm_unpackhi_epi64(ab_01, cd_01);+ __m128i abcd_2 = _mm_unpacklo_epi64(ab_23, cd_23);+ __m128i abcd_3 = _mm_unpackhi_epi64(ab_23, cd_23);++ vecs[0] = abcd_0;+ vecs[1] = abcd_1;+ vecs[2] = abcd_2;+ vecs[3] = abcd_3;+}++INLINE void transpose_msg_vecs4(const uint8_t *const *inputs,+ size_t block_offset, __m128i out[16]) {+ out[0] = loadu_128(&inputs[0][block_offset + 0 * sizeof(__m128i)]);+ out[1] = loadu_128(&inputs[1][block_offset + 0 * sizeof(__m128i)]);+ out[2] = loadu_128(&inputs[2][block_offset + 0 * sizeof(__m128i)]);+ out[3] = loadu_128(&inputs[3][block_offset + 0 * sizeof(__m128i)]);+ out[4] = loadu_128(&inputs[0][block_offset + 1 * sizeof(__m128i)]);+ out[5] = loadu_128(&inputs[1][block_offset + 1 * sizeof(__m128i)]);+ out[6] = loadu_128(&inputs[2][block_offset + 1 * sizeof(__m128i)]);+ out[7] = loadu_128(&inputs[3][block_offset + 1 * sizeof(__m128i)]);+ out[8] = loadu_128(&inputs[0][block_offset + 2 * sizeof(__m128i)]);+ out[9] = loadu_128(&inputs[1][block_offset + 2 * sizeof(__m128i)]);+ out[10] = loadu_128(&inputs[2][block_offset + 2 * sizeof(__m128i)]);+ out[11] = loadu_128(&inputs[3][block_offset + 2 * sizeof(__m128i)]);+ out[12] = loadu_128(&inputs[0][block_offset + 3 * sizeof(__m128i)]);+ out[13] = loadu_128(&inputs[1][block_offset + 3 * sizeof(__m128i)]);+ out[14] = loadu_128(&inputs[2][block_offset + 3 * sizeof(__m128i)]);+ out[15] = loadu_128(&inputs[3][block_offset + 3 * sizeof(__m128i)]);+ for (size_t i = 0; i < 4; ++i) {+ _mm_prefetch((const void *)&inputs[i][block_offset + 256], _MM_HINT_T0);+ }+ transpose_vecs_128(&out[0]);+ transpose_vecs_128(&out[4]);+ transpose_vecs_128(&out[8]);+ transpose_vecs_128(&out[12]);+}++INLINE void load_counters4(uint64_t counter, bool increment_counter,+ __m128i *out_lo, __m128i *out_hi) {+ uint64_t mask = (increment_counter ? ~0 : 0);+ __m256i mask_vec = _mm256_set1_epi64x(mask);+ __m256i deltas = _mm256_setr_epi64x(0, 1, 2, 3);+ deltas = _mm256_and_si256(mask_vec, deltas);+ __m256i counters =+ _mm256_add_epi64(_mm256_set1_epi64x((int64_t)counter), deltas);+ *out_lo = _mm256_cvtepi64_epi32(counters);+ *out_hi = _mm256_cvtepi64_epi32(_mm256_srli_epi64(counters, 32));+}++static+void blake3_hash4_avx512(const uint8_t *const *inputs, size_t blocks,+ const uint32_t key[8], uint64_t counter,+ bool increment_counter, uint8_t flags,+ uint8_t flags_start, uint8_t flags_end, uint8_t *out) {+ __m128i h_vecs[8] = {+ set1_128(key[0]), set1_128(key[1]), set1_128(key[2]), set1_128(key[3]),+ set1_128(key[4]), set1_128(key[5]), set1_128(key[6]), set1_128(key[7]),+ };+ __m128i counter_low_vec, counter_high_vec;+ load_counters4(counter, increment_counter, &counter_low_vec,+ &counter_high_vec);+ uint8_t block_flags = flags | flags_start;++ for (size_t block = 0; block < blocks; block++) {+ if (block + 1 == blocks) {+ block_flags |= flags_end;+ }+ __m128i block_len_vec = set1_128(BLAKE3_BLOCK_LEN);+ __m128i block_flags_vec = set1_128(block_flags);+ __m128i msg_vecs[16];+ transpose_msg_vecs4(inputs, block * BLAKE3_BLOCK_LEN, msg_vecs);++ __m128i v[16] = {+ h_vecs[0], h_vecs[1], h_vecs[2], h_vecs[3],+ h_vecs[4], h_vecs[5], h_vecs[6], h_vecs[7],+ set1_128(IV[0]), set1_128(IV[1]), set1_128(IV[2]), set1_128(IV[3]),+ counter_low_vec, counter_high_vec, block_len_vec, block_flags_vec,+ };+ round_fn4(v, msg_vecs, 0);+ round_fn4(v, msg_vecs, 1);+ round_fn4(v, msg_vecs, 2);+ round_fn4(v, msg_vecs, 3);+ round_fn4(v, msg_vecs, 4);+ round_fn4(v, msg_vecs, 5);+ round_fn4(v, msg_vecs, 6);+ h_vecs[0] = xor_128(v[0], v[8]);+ h_vecs[1] = xor_128(v[1], v[9]);+ h_vecs[2] = xor_128(v[2], v[10]);+ h_vecs[3] = xor_128(v[3], v[11]);+ h_vecs[4] = xor_128(v[4], v[12]);+ h_vecs[5] = xor_128(v[5], v[13]);+ h_vecs[6] = xor_128(v[6], v[14]);+ h_vecs[7] = xor_128(v[7], v[15]);++ block_flags = flags;+ }++ transpose_vecs_128(&h_vecs[0]);+ transpose_vecs_128(&h_vecs[4]);+ // The first four vecs now contain the first half of each output, and the+ // second four vecs contain the second half of each output.+ storeu_128(h_vecs[0], &out[0 * sizeof(__m128i)]);+ storeu_128(h_vecs[4], &out[1 * sizeof(__m128i)]);+ storeu_128(h_vecs[1], &out[2 * sizeof(__m128i)]);+ storeu_128(h_vecs[5], &out[3 * sizeof(__m128i)]);+ storeu_128(h_vecs[2], &out[4 * sizeof(__m128i)]);+ storeu_128(h_vecs[6], &out[5 * sizeof(__m128i)]);+ storeu_128(h_vecs[3], &out[6 * sizeof(__m128i)]);+ storeu_128(h_vecs[7], &out[7 * sizeof(__m128i)]);+}++static+void blake3_xof4_avx512(const uint32_t cv[8],+ const uint8_t block[BLAKE3_BLOCK_LEN],+ uint8_t block_len, uint64_t counter, uint8_t flags,+ uint8_t out[4 * 64]) {+ __m128i h_vecs[8] = {+ set1_128(cv[0]), set1_128(cv[1]), set1_128(cv[2]), set1_128(cv[3]),+ set1_128(cv[4]), set1_128(cv[5]), set1_128(cv[6]), set1_128(cv[7]),+ };+ uint32_t block_words[16];+ load_block_words(block, block_words);+ __m128i msg_vecs[16];+ for (size_t i = 0; i < 16; i++) {+ msg_vecs[i] = set1_128(block_words[i]);+ }+ __m128i counter_low_vec, counter_high_vec;+ load_counters4(counter, true, &counter_low_vec, &counter_high_vec);+ __m128i block_len_vec = set1_128(block_len);+ __m128i block_flags_vec = set1_128(flags);+ __m128i v[16] = {+ h_vecs[0], h_vecs[1], h_vecs[2], h_vecs[3],+ h_vecs[4], h_vecs[5], h_vecs[6], h_vecs[7],+ set1_128(IV[0]), set1_128(IV[1]), set1_128(IV[2]), set1_128(IV[3]),+ counter_low_vec, counter_high_vec, block_len_vec, block_flags_vec,+ };+ round_fn4(v, msg_vecs, 0);+ round_fn4(v, msg_vecs, 1);+ round_fn4(v, msg_vecs, 2);+ round_fn4(v, msg_vecs, 3);+ round_fn4(v, msg_vecs, 4);+ round_fn4(v, msg_vecs, 5);+ round_fn4(v, msg_vecs, 6);+ for (size_t i = 0; i < 8; i++) {+ v[i] = xor_128(v[i], v[i+8]);+ v[i+8] = xor_128(v[i+8], h_vecs[i]);+ }+ transpose_vecs_128(&v[0]);+ transpose_vecs_128(&v[4]);+ transpose_vecs_128(&v[8]);+ transpose_vecs_128(&v[12]);+ for (size_t i = 0; i < 4; i++) {+ storeu_128(v[i+ 0], &out[(4*i+0) * sizeof(__m128i)]);+ storeu_128(v[i+ 4], &out[(4*i+1) * sizeof(__m128i)]);+ storeu_128(v[i+ 8], &out[(4*i+2) * sizeof(__m128i)]);+ storeu_128(v[i+12], &out[(4*i+3) * sizeof(__m128i)]);+ }+}++/*+ * ----------------------------------------------------------------------------+ * hash8_avx512+ * ----------------------------------------------------------------------------+ */++INLINE void round_fn8(__m256i v[16], __m256i m[16], size_t r) {+ v[0] = add_256(v[0], m[(size_t)MSG_SCHEDULE[r][0]]);+ v[1] = add_256(v[1], m[(size_t)MSG_SCHEDULE[r][2]]);+ v[2] = add_256(v[2], m[(size_t)MSG_SCHEDULE[r][4]]);+ v[3] = add_256(v[3], m[(size_t)MSG_SCHEDULE[r][6]]);+ v[0] = add_256(v[0], v[4]);+ v[1] = add_256(v[1], v[5]);+ v[2] = add_256(v[2], v[6]);+ v[3] = add_256(v[3], v[7]);+ v[12] = xor_256(v[12], v[0]);+ v[13] = xor_256(v[13], v[1]);+ v[14] = xor_256(v[14], v[2]);+ v[15] = xor_256(v[15], v[3]);+ v[12] = rot16_256(v[12]);+ v[13] = rot16_256(v[13]);+ v[14] = rot16_256(v[14]);+ v[15] = rot16_256(v[15]);+ v[8] = add_256(v[8], v[12]);+ v[9] = add_256(v[9], v[13]);+ v[10] = add_256(v[10], v[14]);+ v[11] = add_256(v[11], v[15]);+ v[4] = xor_256(v[4], v[8]);+ v[5] = xor_256(v[5], v[9]);+ v[6] = xor_256(v[6], v[10]);+ v[7] = xor_256(v[7], v[11]);+ v[4] = rot12_256(v[4]);+ v[5] = rot12_256(v[5]);+ v[6] = rot12_256(v[6]);+ v[7] = rot12_256(v[7]);+ v[0] = add_256(v[0], m[(size_t)MSG_SCHEDULE[r][1]]);+ v[1] = add_256(v[1], m[(size_t)MSG_SCHEDULE[r][3]]);+ v[2] = add_256(v[2], m[(size_t)MSG_SCHEDULE[r][5]]);+ v[3] = add_256(v[3], m[(size_t)MSG_SCHEDULE[r][7]]);+ v[0] = add_256(v[0], v[4]);+ v[1] = add_256(v[1], v[5]);+ v[2] = add_256(v[2], v[6]);+ v[3] = add_256(v[3], v[7]);+ v[12] = xor_256(v[12], v[0]);+ v[13] = xor_256(v[13], v[1]);+ v[14] = xor_256(v[14], v[2]);+ v[15] = xor_256(v[15], v[3]);+ v[12] = rot8_256(v[12]);+ v[13] = rot8_256(v[13]);+ v[14] = rot8_256(v[14]);+ v[15] = rot8_256(v[15]);+ v[8] = add_256(v[8], v[12]);+ v[9] = add_256(v[9], v[13]);+ v[10] = add_256(v[10], v[14]);+ v[11] = add_256(v[11], v[15]);+ v[4] = xor_256(v[4], v[8]);+ v[5] = xor_256(v[5], v[9]);+ v[6] = xor_256(v[6], v[10]);+ v[7] = xor_256(v[7], v[11]);+ v[4] = rot7_256(v[4]);+ v[5] = rot7_256(v[5]);+ v[6] = rot7_256(v[6]);+ v[7] = rot7_256(v[7]);++ v[0] = add_256(v[0], m[(size_t)MSG_SCHEDULE[r][8]]);+ v[1] = add_256(v[1], m[(size_t)MSG_SCHEDULE[r][10]]);+ v[2] = add_256(v[2], m[(size_t)MSG_SCHEDULE[r][12]]);+ v[3] = add_256(v[3], m[(size_t)MSG_SCHEDULE[r][14]]);+ v[0] = add_256(v[0], v[5]);+ v[1] = add_256(v[1], v[6]);+ v[2] = add_256(v[2], v[7]);+ v[3] = add_256(v[3], v[4]);+ v[15] = xor_256(v[15], v[0]);+ v[12] = xor_256(v[12], v[1]);+ v[13] = xor_256(v[13], v[2]);+ v[14] = xor_256(v[14], v[3]);+ v[15] = rot16_256(v[15]);+ v[12] = rot16_256(v[12]);+ v[13] = rot16_256(v[13]);+ v[14] = rot16_256(v[14]);+ v[10] = add_256(v[10], v[15]);+ v[11] = add_256(v[11], v[12]);+ v[8] = add_256(v[8], v[13]);+ v[9] = add_256(v[9], v[14]);+ v[5] = xor_256(v[5], v[10]);+ v[6] = xor_256(v[6], v[11]);+ v[7] = xor_256(v[7], v[8]);+ v[4] = xor_256(v[4], v[9]);+ v[5] = rot12_256(v[5]);+ v[6] = rot12_256(v[6]);+ v[7] = rot12_256(v[7]);+ v[4] = rot12_256(v[4]);+ v[0] = add_256(v[0], m[(size_t)MSG_SCHEDULE[r][9]]);+ v[1] = add_256(v[1], m[(size_t)MSG_SCHEDULE[r][11]]);+ v[2] = add_256(v[2], m[(size_t)MSG_SCHEDULE[r][13]]);+ v[3] = add_256(v[3], m[(size_t)MSG_SCHEDULE[r][15]]);+ v[0] = add_256(v[0], v[5]);+ v[1] = add_256(v[1], v[6]);+ v[2] = add_256(v[2], v[7]);+ v[3] = add_256(v[3], v[4]);+ v[15] = xor_256(v[15], v[0]);+ v[12] = xor_256(v[12], v[1]);+ v[13] = xor_256(v[13], v[2]);+ v[14] = xor_256(v[14], v[3]);+ v[15] = rot8_256(v[15]);+ v[12] = rot8_256(v[12]);+ v[13] = rot8_256(v[13]);+ v[14] = rot8_256(v[14]);+ v[10] = add_256(v[10], v[15]);+ v[11] = add_256(v[11], v[12]);+ v[8] = add_256(v[8], v[13]);+ v[9] = add_256(v[9], v[14]);+ v[5] = xor_256(v[5], v[10]);+ v[6] = xor_256(v[6], v[11]);+ v[7] = xor_256(v[7], v[8]);+ v[4] = xor_256(v[4], v[9]);+ v[5] = rot7_256(v[5]);+ v[6] = rot7_256(v[6]);+ v[7] = rot7_256(v[7]);+ v[4] = rot7_256(v[4]);+}++INLINE void transpose_vecs_256(__m256i vecs[8]) {+ // Interleave 32-bit lanes. The low unpack is lanes 00/11/44/55, and the high+ // is 22/33/66/77.+ __m256i ab_0145 = _mm256_unpacklo_epi32(vecs[0], vecs[1]);+ __m256i ab_2367 = _mm256_unpackhi_epi32(vecs[0], vecs[1]);+ __m256i cd_0145 = _mm256_unpacklo_epi32(vecs[2], vecs[3]);+ __m256i cd_2367 = _mm256_unpackhi_epi32(vecs[2], vecs[3]);+ __m256i ef_0145 = _mm256_unpacklo_epi32(vecs[4], vecs[5]);+ __m256i ef_2367 = _mm256_unpackhi_epi32(vecs[4], vecs[5]);+ __m256i gh_0145 = _mm256_unpacklo_epi32(vecs[6], vecs[7]);+ __m256i gh_2367 = _mm256_unpackhi_epi32(vecs[6], vecs[7]);++ // Interleave 64-bit lanes. The low unpack is lanes 00/22 and the high is+ // 11/33.+ __m256i abcd_04 = _mm256_unpacklo_epi64(ab_0145, cd_0145);+ __m256i abcd_15 = _mm256_unpackhi_epi64(ab_0145, cd_0145);+ __m256i abcd_26 = _mm256_unpacklo_epi64(ab_2367, cd_2367);+ __m256i abcd_37 = _mm256_unpackhi_epi64(ab_2367, cd_2367);+ __m256i efgh_04 = _mm256_unpacklo_epi64(ef_0145, gh_0145);+ __m256i efgh_15 = _mm256_unpackhi_epi64(ef_0145, gh_0145);+ __m256i efgh_26 = _mm256_unpacklo_epi64(ef_2367, gh_2367);+ __m256i efgh_37 = _mm256_unpackhi_epi64(ef_2367, gh_2367);++ // Interleave 128-bit lanes.+ vecs[0] = _mm256_permute2x128_si256(abcd_04, efgh_04, 0x20);+ vecs[1] = _mm256_permute2x128_si256(abcd_15, efgh_15, 0x20);+ vecs[2] = _mm256_permute2x128_si256(abcd_26, efgh_26, 0x20);+ vecs[3] = _mm256_permute2x128_si256(abcd_37, efgh_37, 0x20);+ vecs[4] = _mm256_permute2x128_si256(abcd_04, efgh_04, 0x31);+ vecs[5] = _mm256_permute2x128_si256(abcd_15, efgh_15, 0x31);+ vecs[6] = _mm256_permute2x128_si256(abcd_26, efgh_26, 0x31);+ vecs[7] = _mm256_permute2x128_si256(abcd_37, efgh_37, 0x31);+}++INLINE void transpose_msg_vecs8(const uint8_t *const *inputs,+ size_t block_offset, __m256i out[16]) {+ out[0] = loadu_256(&inputs[0][block_offset + 0 * sizeof(__m256i)]);+ out[1] = loadu_256(&inputs[1][block_offset + 0 * sizeof(__m256i)]);+ out[2] = loadu_256(&inputs[2][block_offset + 0 * sizeof(__m256i)]);+ out[3] = loadu_256(&inputs[3][block_offset + 0 * sizeof(__m256i)]);+ out[4] = loadu_256(&inputs[4][block_offset + 0 * sizeof(__m256i)]);+ out[5] = loadu_256(&inputs[5][block_offset + 0 * sizeof(__m256i)]);+ out[6] = loadu_256(&inputs[6][block_offset + 0 * sizeof(__m256i)]);+ out[7] = loadu_256(&inputs[7][block_offset + 0 * sizeof(__m256i)]);+ out[8] = loadu_256(&inputs[0][block_offset + 1 * sizeof(__m256i)]);+ out[9] = loadu_256(&inputs[1][block_offset + 1 * sizeof(__m256i)]);+ out[10] = loadu_256(&inputs[2][block_offset + 1 * sizeof(__m256i)]);+ out[11] = loadu_256(&inputs[3][block_offset + 1 * sizeof(__m256i)]);+ out[12] = loadu_256(&inputs[4][block_offset + 1 * sizeof(__m256i)]);+ out[13] = loadu_256(&inputs[5][block_offset + 1 * sizeof(__m256i)]);+ out[14] = loadu_256(&inputs[6][block_offset + 1 * sizeof(__m256i)]);+ out[15] = loadu_256(&inputs[7][block_offset + 1 * sizeof(__m256i)]);+ for (size_t i = 0; i < 8; ++i) {+ _mm_prefetch((const void *)&inputs[i][block_offset + 256], _MM_HINT_T0);+ }+ transpose_vecs_256(&out[0]);+ transpose_vecs_256(&out[8]);+}++INLINE void load_counters8(uint64_t counter, bool increment_counter,+ __m256i *out_lo, __m256i *out_hi) {+ uint64_t mask = (increment_counter ? ~0 : 0);+ __m512i mask_vec = _mm512_set1_epi64(mask);+ __m512i deltas = _mm512_setr_epi64(0, 1, 2, 3, 4, 5, 6, 7);+ deltas = _mm512_and_si512(mask_vec, deltas);+ __m512i counters =+ _mm512_add_epi64(_mm512_set1_epi64((int64_t)counter), deltas);+ *out_lo = _mm512_cvtepi64_epi32(counters);+ *out_hi = _mm512_cvtepi64_epi32(_mm512_srli_epi64(counters, 32));+}++static+void blake3_hash8_avx512(const uint8_t *const *inputs, size_t blocks,+ const uint32_t key[8], uint64_t counter,+ bool increment_counter, uint8_t flags,+ uint8_t flags_start, uint8_t flags_end, uint8_t *out) {+ __m256i h_vecs[8] = {+ set1_256(key[0]), set1_256(key[1]), set1_256(key[2]), set1_256(key[3]),+ set1_256(key[4]), set1_256(key[5]), set1_256(key[6]), set1_256(key[7]),+ };+ __m256i counter_low_vec, counter_high_vec;+ load_counters8(counter, increment_counter, &counter_low_vec,+ &counter_high_vec);+ uint8_t block_flags = flags | flags_start;++ for (size_t block = 0; block < blocks; block++) {+ if (block + 1 == blocks) {+ block_flags |= flags_end;+ }+ __m256i block_len_vec = set1_256(BLAKE3_BLOCK_LEN);+ __m256i block_flags_vec = set1_256(block_flags);+ __m256i msg_vecs[16];+ transpose_msg_vecs8(inputs, block * BLAKE3_BLOCK_LEN, msg_vecs);++ __m256i v[16] = {+ h_vecs[0], h_vecs[1], h_vecs[2], h_vecs[3],+ h_vecs[4], h_vecs[5], h_vecs[6], h_vecs[7],+ set1_256(IV[0]), set1_256(IV[1]), set1_256(IV[2]), set1_256(IV[3]),+ counter_low_vec, counter_high_vec, block_len_vec, block_flags_vec,+ };+ round_fn8(v, msg_vecs, 0);+ round_fn8(v, msg_vecs, 1);+ round_fn8(v, msg_vecs, 2);+ round_fn8(v, msg_vecs, 3);+ round_fn8(v, msg_vecs, 4);+ round_fn8(v, msg_vecs, 5);+ round_fn8(v, msg_vecs, 6);+ h_vecs[0] = xor_256(v[0], v[8]);+ h_vecs[1] = xor_256(v[1], v[9]);+ h_vecs[2] = xor_256(v[2], v[10]);+ h_vecs[3] = xor_256(v[3], v[11]);+ h_vecs[4] = xor_256(v[4], v[12]);+ h_vecs[5] = xor_256(v[5], v[13]);+ h_vecs[6] = xor_256(v[6], v[14]);+ h_vecs[7] = xor_256(v[7], v[15]);++ block_flags = flags;+ }++ transpose_vecs_256(h_vecs);+ storeu_256(h_vecs[0], &out[0 * sizeof(__m256i)]);+ storeu_256(h_vecs[1], &out[1 * sizeof(__m256i)]);+ storeu_256(h_vecs[2], &out[2 * sizeof(__m256i)]);+ storeu_256(h_vecs[3], &out[3 * sizeof(__m256i)]);+ storeu_256(h_vecs[4], &out[4 * sizeof(__m256i)]);+ storeu_256(h_vecs[5], &out[5 * sizeof(__m256i)]);+ storeu_256(h_vecs[6], &out[6 * sizeof(__m256i)]);+ storeu_256(h_vecs[7], &out[7 * sizeof(__m256i)]);+}++static+void blake3_xof8_avx512(const uint32_t cv[8],+ const uint8_t block[BLAKE3_BLOCK_LEN],+ uint8_t block_len, uint64_t counter, uint8_t flags,+ uint8_t out[8 * 64]) {+ __m256i h_vecs[8] = {+ set1_256(cv[0]), set1_256(cv[1]), set1_256(cv[2]), set1_256(cv[3]),+ set1_256(cv[4]), set1_256(cv[5]), set1_256(cv[6]), set1_256(cv[7]),+ };+ uint32_t block_words[16];+ load_block_words(block, block_words);+ __m256i msg_vecs[16];+ for (size_t i = 0; i < 16; i++) {+ msg_vecs[i] = set1_256(block_words[i]);+ }+ __m256i counter_low_vec, counter_high_vec;+ load_counters8(counter, true, &counter_low_vec, &counter_high_vec);+ __m256i block_len_vec = set1_256(block_len);+ __m256i block_flags_vec = set1_256(flags);+ __m256i v[16] = {+ h_vecs[0], h_vecs[1], h_vecs[2], h_vecs[3],+ h_vecs[4], h_vecs[5], h_vecs[6], h_vecs[7],+ set1_256(IV[0]), set1_256(IV[1]), set1_256(IV[2]), set1_256(IV[3]),+ counter_low_vec, counter_high_vec, block_len_vec, block_flags_vec,+ };+ round_fn8(v, msg_vecs, 0);+ round_fn8(v, msg_vecs, 1);+ round_fn8(v, msg_vecs, 2);+ round_fn8(v, msg_vecs, 3);+ round_fn8(v, msg_vecs, 4);+ round_fn8(v, msg_vecs, 5);+ round_fn8(v, msg_vecs, 6);+ for (size_t i = 0; i < 8; i++) {+ v[i] = xor_256(v[i], v[i+8]);+ v[i+8] = xor_256(v[i+8], h_vecs[i]);+ }+ transpose_vecs_256(&v[0]);+ transpose_vecs_256(&v[8]);+ for (size_t i = 0; i < 8; i++) {+ storeu_256(v[i+0], &out[(2*i+0) * sizeof(__m256i)]);+ storeu_256(v[i+8], &out[(2*i+1) * sizeof(__m256i)]);+ }+}++/*+ * ----------------------------------------------------------------------------+ * hash16_avx512+ * ----------------------------------------------------------------------------+ */++INLINE void round_fn16(__m512i v[16], __m512i m[16], size_t r) {+ v[0] = add_512(v[0], m[(size_t)MSG_SCHEDULE[r][0]]);+ v[1] = add_512(v[1], m[(size_t)MSG_SCHEDULE[r][2]]);+ v[2] = add_512(v[2], m[(size_t)MSG_SCHEDULE[r][4]]);+ v[3] = add_512(v[3], m[(size_t)MSG_SCHEDULE[r][6]]);+ v[0] = add_512(v[0], v[4]);+ v[1] = add_512(v[1], v[5]);+ v[2] = add_512(v[2], v[6]);+ v[3] = add_512(v[3], v[7]);+ v[12] = xor_512(v[12], v[0]);+ v[13] = xor_512(v[13], v[1]);+ v[14] = xor_512(v[14], v[2]);+ v[15] = xor_512(v[15], v[3]);+ v[12] = rot16_512(v[12]);+ v[13] = rot16_512(v[13]);+ v[14] = rot16_512(v[14]);+ v[15] = rot16_512(v[15]);+ v[8] = add_512(v[8], v[12]);+ v[9] = add_512(v[9], v[13]);+ v[10] = add_512(v[10], v[14]);+ v[11] = add_512(v[11], v[15]);+ v[4] = xor_512(v[4], v[8]);+ v[5] = xor_512(v[5], v[9]);+ v[6] = xor_512(v[6], v[10]);+ v[7] = xor_512(v[7], v[11]);+ v[4] = rot12_512(v[4]);+ v[5] = rot12_512(v[5]);+ v[6] = rot12_512(v[6]);+ v[7] = rot12_512(v[7]);+ v[0] = add_512(v[0], m[(size_t)MSG_SCHEDULE[r][1]]);+ v[1] = add_512(v[1], m[(size_t)MSG_SCHEDULE[r][3]]);+ v[2] = add_512(v[2], m[(size_t)MSG_SCHEDULE[r][5]]);+ v[3] = add_512(v[3], m[(size_t)MSG_SCHEDULE[r][7]]);+ v[0] = add_512(v[0], v[4]);+ v[1] = add_512(v[1], v[5]);+ v[2] = add_512(v[2], v[6]);+ v[3] = add_512(v[3], v[7]);+ v[12] = xor_512(v[12], v[0]);+ v[13] = xor_512(v[13], v[1]);+ v[14] = xor_512(v[14], v[2]);+ v[15] = xor_512(v[15], v[3]);+ v[12] = rot8_512(v[12]);+ v[13] = rot8_512(v[13]);+ v[14] = rot8_512(v[14]);+ v[15] = rot8_512(v[15]);+ v[8] = add_512(v[8], v[12]);+ v[9] = add_512(v[9], v[13]);+ v[10] = add_512(v[10], v[14]);+ v[11] = add_512(v[11], v[15]);+ v[4] = xor_512(v[4], v[8]);+ v[5] = xor_512(v[5], v[9]);+ v[6] = xor_512(v[6], v[10]);+ v[7] = xor_512(v[7], v[11]);+ v[4] = rot7_512(v[4]);+ v[5] = rot7_512(v[5]);+ v[6] = rot7_512(v[6]);+ v[7] = rot7_512(v[7]);++ v[0] = add_512(v[0], m[(size_t)MSG_SCHEDULE[r][8]]);+ v[1] = add_512(v[1], m[(size_t)MSG_SCHEDULE[r][10]]);+ v[2] = add_512(v[2], m[(size_t)MSG_SCHEDULE[r][12]]);+ v[3] = add_512(v[3], m[(size_t)MSG_SCHEDULE[r][14]]);+ v[0] = add_512(v[0], v[5]);+ v[1] = add_512(v[1], v[6]);+ v[2] = add_512(v[2], v[7]);+ v[3] = add_512(v[3], v[4]);+ v[15] = xor_512(v[15], v[0]);+ v[12] = xor_512(v[12], v[1]);+ v[13] = xor_512(v[13], v[2]);+ v[14] = xor_512(v[14], v[3]);+ v[15] = rot16_512(v[15]);+ v[12] = rot16_512(v[12]);+ v[13] = rot16_512(v[13]);+ v[14] = rot16_512(v[14]);+ v[10] = add_512(v[10], v[15]);+ v[11] = add_512(v[11], v[12]);+ v[8] = add_512(v[8], v[13]);+ v[9] = add_512(v[9], v[14]);+ v[5] = xor_512(v[5], v[10]);+ v[6] = xor_512(v[6], v[11]);+ v[7] = xor_512(v[7], v[8]);+ v[4] = xor_512(v[4], v[9]);+ v[5] = rot12_512(v[5]);+ v[6] = rot12_512(v[6]);+ v[7] = rot12_512(v[7]);+ v[4] = rot12_512(v[4]);+ v[0] = add_512(v[0], m[(size_t)MSG_SCHEDULE[r][9]]);+ v[1] = add_512(v[1], m[(size_t)MSG_SCHEDULE[r][11]]);+ v[2] = add_512(v[2], m[(size_t)MSG_SCHEDULE[r][13]]);+ v[3] = add_512(v[3], m[(size_t)MSG_SCHEDULE[r][15]]);+ v[0] = add_512(v[0], v[5]);+ v[1] = add_512(v[1], v[6]);+ v[2] = add_512(v[2], v[7]);+ v[3] = add_512(v[3], v[4]);+ v[15] = xor_512(v[15], v[0]);+ v[12] = xor_512(v[12], v[1]);+ v[13] = xor_512(v[13], v[2]);+ v[14] = xor_512(v[14], v[3]);+ v[15] = rot8_512(v[15]);+ v[12] = rot8_512(v[12]);+ v[13] = rot8_512(v[13]);+ v[14] = rot8_512(v[14]);+ v[10] = add_512(v[10], v[15]);+ v[11] = add_512(v[11], v[12]);+ v[8] = add_512(v[8], v[13]);+ v[9] = add_512(v[9], v[14]);+ v[5] = xor_512(v[5], v[10]);+ v[6] = xor_512(v[6], v[11]);+ v[7] = xor_512(v[7], v[8]);+ v[4] = xor_512(v[4], v[9]);+ v[5] = rot7_512(v[5]);+ v[6] = rot7_512(v[6]);+ v[7] = rot7_512(v[7]);+ v[4] = rot7_512(v[4]);+}++// 0b10001000, or lanes a0/a2/b0/b2 in little-endian order+#define LO_IMM8 0x88++INLINE __m512i unpack_lo_128(__m512i a, __m512i b) {+ return _mm512_shuffle_i32x4(a, b, LO_IMM8);+}++// 0b11011101, or lanes a1/a3/b1/b3 in little-endian order+#define HI_IMM8 0xdd++INLINE __m512i unpack_hi_128(__m512i a, __m512i b) {+ return _mm512_shuffle_i32x4(a, b, HI_IMM8);+}++INLINE void transpose_vecs_512(__m512i vecs[16]) {+ // Interleave 32-bit lanes. The _0 unpack is lanes+ // 0/0/1/1/4/4/5/5/8/8/9/9/12/12/13/13, and the _2 unpack is lanes+ // 2/2/3/3/6/6/7/7/10/10/11/11/14/14/15/15.+ __m512i ab_0 = _mm512_unpacklo_epi32(vecs[0], vecs[1]);+ __m512i ab_2 = _mm512_unpackhi_epi32(vecs[0], vecs[1]);+ __m512i cd_0 = _mm512_unpacklo_epi32(vecs[2], vecs[3]);+ __m512i cd_2 = _mm512_unpackhi_epi32(vecs[2], vecs[3]);+ __m512i ef_0 = _mm512_unpacklo_epi32(vecs[4], vecs[5]);+ __m512i ef_2 = _mm512_unpackhi_epi32(vecs[4], vecs[5]);+ __m512i gh_0 = _mm512_unpacklo_epi32(vecs[6], vecs[7]);+ __m512i gh_2 = _mm512_unpackhi_epi32(vecs[6], vecs[7]);+ __m512i ij_0 = _mm512_unpacklo_epi32(vecs[8], vecs[9]);+ __m512i ij_2 = _mm512_unpackhi_epi32(vecs[8], vecs[9]);+ __m512i kl_0 = _mm512_unpacklo_epi32(vecs[10], vecs[11]);+ __m512i kl_2 = _mm512_unpackhi_epi32(vecs[10], vecs[11]);+ __m512i mn_0 = _mm512_unpacklo_epi32(vecs[12], vecs[13]);+ __m512i mn_2 = _mm512_unpackhi_epi32(vecs[12], vecs[13]);+ __m512i op_0 = _mm512_unpacklo_epi32(vecs[14], vecs[15]);+ __m512i op_2 = _mm512_unpackhi_epi32(vecs[14], vecs[15]);++ // Interleave 64-bit lanes. The _0 unpack is lanes+ // 0/0/0/0/4/4/4/4/8/8/8/8/12/12/12/12, the _1 unpack is lanes+ // 1/1/1/1/5/5/5/5/9/9/9/9/13/13/13/13, the _2 unpack is lanes+ // 2/2/2/2/6/6/6/6/10/10/10/10/14/14/14/14, and the _3 unpack is lanes+ // 3/3/3/3/7/7/7/7/11/11/11/11/15/15/15/15.+ __m512i abcd_0 = _mm512_unpacklo_epi64(ab_0, cd_0);+ __m512i abcd_1 = _mm512_unpackhi_epi64(ab_0, cd_0);+ __m512i abcd_2 = _mm512_unpacklo_epi64(ab_2, cd_2);+ __m512i abcd_3 = _mm512_unpackhi_epi64(ab_2, cd_2);+ __m512i efgh_0 = _mm512_unpacklo_epi64(ef_0, gh_0);+ __m512i efgh_1 = _mm512_unpackhi_epi64(ef_0, gh_0);+ __m512i efgh_2 = _mm512_unpacklo_epi64(ef_2, gh_2);+ __m512i efgh_3 = _mm512_unpackhi_epi64(ef_2, gh_2);+ __m512i ijkl_0 = _mm512_unpacklo_epi64(ij_0, kl_0);+ __m512i ijkl_1 = _mm512_unpackhi_epi64(ij_0, kl_0);+ __m512i ijkl_2 = _mm512_unpacklo_epi64(ij_2, kl_2);+ __m512i ijkl_3 = _mm512_unpackhi_epi64(ij_2, kl_2);+ __m512i mnop_0 = _mm512_unpacklo_epi64(mn_0, op_0);+ __m512i mnop_1 = _mm512_unpackhi_epi64(mn_0, op_0);+ __m512i mnop_2 = _mm512_unpacklo_epi64(mn_2, op_2);+ __m512i mnop_3 = _mm512_unpackhi_epi64(mn_2, op_2);++ // Interleave 128-bit lanes. The _0 unpack is+ // 0/0/0/0/8/8/8/8/0/0/0/0/8/8/8/8, the _1 unpack is+ // 1/1/1/1/9/9/9/9/1/1/1/1/9/9/9/9, and so on.+ __m512i abcdefgh_0 = unpack_lo_128(abcd_0, efgh_0);+ __m512i abcdefgh_1 = unpack_lo_128(abcd_1, efgh_1);+ __m512i abcdefgh_2 = unpack_lo_128(abcd_2, efgh_2);+ __m512i abcdefgh_3 = unpack_lo_128(abcd_3, efgh_3);+ __m512i abcdefgh_4 = unpack_hi_128(abcd_0, efgh_0);+ __m512i abcdefgh_5 = unpack_hi_128(abcd_1, efgh_1);+ __m512i abcdefgh_6 = unpack_hi_128(abcd_2, efgh_2);+ __m512i abcdefgh_7 = unpack_hi_128(abcd_3, efgh_3);+ __m512i ijklmnop_0 = unpack_lo_128(ijkl_0, mnop_0);+ __m512i ijklmnop_1 = unpack_lo_128(ijkl_1, mnop_1);+ __m512i ijklmnop_2 = unpack_lo_128(ijkl_2, mnop_2);+ __m512i ijklmnop_3 = unpack_lo_128(ijkl_3, mnop_3);+ __m512i ijklmnop_4 = unpack_hi_128(ijkl_0, mnop_0);+ __m512i ijklmnop_5 = unpack_hi_128(ijkl_1, mnop_1);+ __m512i ijklmnop_6 = unpack_hi_128(ijkl_2, mnop_2);+ __m512i ijklmnop_7 = unpack_hi_128(ijkl_3, mnop_3);++ // Interleave 128-bit lanes again for the final outputs.+ vecs[0] = unpack_lo_128(abcdefgh_0, ijklmnop_0);+ vecs[1] = unpack_lo_128(abcdefgh_1, ijklmnop_1);+ vecs[2] = unpack_lo_128(abcdefgh_2, ijklmnop_2);+ vecs[3] = unpack_lo_128(abcdefgh_3, ijklmnop_3);+ vecs[4] = unpack_lo_128(abcdefgh_4, ijklmnop_4);+ vecs[5] = unpack_lo_128(abcdefgh_5, ijklmnop_5);+ vecs[6] = unpack_lo_128(abcdefgh_6, ijklmnop_6);+ vecs[7] = unpack_lo_128(abcdefgh_7, ijklmnop_7);+ vecs[8] = unpack_hi_128(abcdefgh_0, ijklmnop_0);+ vecs[9] = unpack_hi_128(abcdefgh_1, ijklmnop_1);+ vecs[10] = unpack_hi_128(abcdefgh_2, ijklmnop_2);+ vecs[11] = unpack_hi_128(abcdefgh_3, ijklmnop_3);+ vecs[12] = unpack_hi_128(abcdefgh_4, ijklmnop_4);+ vecs[13] = unpack_hi_128(abcdefgh_5, ijklmnop_5);+ vecs[14] = unpack_hi_128(abcdefgh_6, ijklmnop_6);+ vecs[15] = unpack_hi_128(abcdefgh_7, ijklmnop_7);+}++INLINE void transpose_msg_vecs16(const uint8_t *const *inputs,+ size_t block_offset, __m512i out[16]) {+ out[0] = loadu_512(&inputs[0][block_offset]);+ out[1] = loadu_512(&inputs[1][block_offset]);+ out[2] = loadu_512(&inputs[2][block_offset]);+ out[3] = loadu_512(&inputs[3][block_offset]);+ out[4] = loadu_512(&inputs[4][block_offset]);+ out[5] = loadu_512(&inputs[5][block_offset]);+ out[6] = loadu_512(&inputs[6][block_offset]);+ out[7] = loadu_512(&inputs[7][block_offset]);+ out[8] = loadu_512(&inputs[8][block_offset]);+ out[9] = loadu_512(&inputs[9][block_offset]);+ out[10] = loadu_512(&inputs[10][block_offset]);+ out[11] = loadu_512(&inputs[11][block_offset]);+ out[12] = loadu_512(&inputs[12][block_offset]);+ out[13] = loadu_512(&inputs[13][block_offset]);+ out[14] = loadu_512(&inputs[14][block_offset]);+ out[15] = loadu_512(&inputs[15][block_offset]);+ for (size_t i = 0; i < 16; ++i) {+ _mm_prefetch((const void *)&inputs[i][block_offset + 256], _MM_HINT_T0);+ }+ transpose_vecs_512(out);+}++INLINE void load_counters16(uint64_t counter, bool increment_counter,+ __m512i *out_lo, __m512i *out_hi) {+ const __m512i mask = _mm512_set1_epi32(-(int32_t)increment_counter);+ const __m512i deltas = _mm512_set_epi32(15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0);+ const __m512i masked_deltas = _mm512_and_si512(deltas, mask);+ const __m512i low_words = _mm512_add_epi32(+ _mm512_set1_epi32((int32_t)counter),+ masked_deltas);+ // The carry bit is 1 if the high bit of the word was 1 before addition and is+ // 0 after.+ // NOTE: It would be a bit more natural to use _mm512_cmp_epu32_mask to+ // compute the carry bits here, and originally we did, but that intrinsic is+ // broken under GCC 5.4. See https://github.com/BLAKE3-team/BLAKE3/issues/271.+ const __m512i carries = _mm512_srli_epi32(+ _mm512_andnot_si512(+ low_words, // 0 after (gets inverted by andnot)+ _mm512_set1_epi32((int32_t)counter)), // and 1 before+ 31);+ const __m512i high_words = _mm512_add_epi32(+ _mm512_set1_epi32((int32_t)(counter >> 32)),+ carries);+ *out_lo = low_words;+ *out_hi = high_words;+}++static+void blake3_hash16_avx512(const uint8_t *const *inputs, size_t blocks,+ const uint32_t key[8], uint64_t counter,+ bool increment_counter, uint8_t flags,+ uint8_t flags_start, uint8_t flags_end,+ uint8_t *out) {+ __m512i h_vecs[8] = {+ set1_512(key[0]), set1_512(key[1]), set1_512(key[2]), set1_512(key[3]),+ set1_512(key[4]), set1_512(key[5]), set1_512(key[6]), set1_512(key[7]),+ };+ __m512i counter_low_vec, counter_high_vec;+ load_counters16(counter, increment_counter, &counter_low_vec,+ &counter_high_vec);+ uint8_t block_flags = flags | flags_start;++ for (size_t block = 0; block < blocks; block++) {+ if (block + 1 == blocks) {+ block_flags |= flags_end;+ }+ __m512i block_len_vec = set1_512(BLAKE3_BLOCK_LEN);+ __m512i block_flags_vec = set1_512(block_flags);+ __m512i msg_vecs[16];+ transpose_msg_vecs16(inputs, block * BLAKE3_BLOCK_LEN, msg_vecs);++ __m512i v[16] = {+ h_vecs[0], h_vecs[1], h_vecs[2], h_vecs[3],+ h_vecs[4], h_vecs[5], h_vecs[6], h_vecs[7],+ set1_512(IV[0]), set1_512(IV[1]), set1_512(IV[2]), set1_512(IV[3]),+ counter_low_vec, counter_high_vec, block_len_vec, block_flags_vec,+ };+ round_fn16(v, msg_vecs, 0);+ round_fn16(v, msg_vecs, 1);+ round_fn16(v, msg_vecs, 2);+ round_fn16(v, msg_vecs, 3);+ round_fn16(v, msg_vecs, 4);+ round_fn16(v, msg_vecs, 5);+ round_fn16(v, msg_vecs, 6);+ h_vecs[0] = xor_512(v[0], v[8]);+ h_vecs[1] = xor_512(v[1], v[9]);+ h_vecs[2] = xor_512(v[2], v[10]);+ h_vecs[3] = xor_512(v[3], v[11]);+ h_vecs[4] = xor_512(v[4], v[12]);+ h_vecs[5] = xor_512(v[5], v[13]);+ h_vecs[6] = xor_512(v[6], v[14]);+ h_vecs[7] = xor_512(v[7], v[15]);++ block_flags = flags;+ }++ // transpose_vecs_512 operates on a 16x16 matrix of words, but we only have 8+ // state vectors. Pad the matrix with zeros. After transposition, store the+ // lower half of each vector.+ __m512i padded[16] = {+ h_vecs[0], h_vecs[1], h_vecs[2], h_vecs[3],+ h_vecs[4], h_vecs[5], h_vecs[6], h_vecs[7],+ set1_512(0), set1_512(0), set1_512(0), set1_512(0),+ set1_512(0), set1_512(0), set1_512(0), set1_512(0),+ };+ transpose_vecs_512(padded);+ _mm256_mask_storeu_epi32(&out[0 * sizeof(__m256i)], (__mmask8)-1, _mm512_castsi512_si256(padded[0]));+ _mm256_mask_storeu_epi32(&out[1 * sizeof(__m256i)], (__mmask8)-1, _mm512_castsi512_si256(padded[1]));+ _mm256_mask_storeu_epi32(&out[2 * sizeof(__m256i)], (__mmask8)-1, _mm512_castsi512_si256(padded[2]));+ _mm256_mask_storeu_epi32(&out[3 * sizeof(__m256i)], (__mmask8)-1, _mm512_castsi512_si256(padded[3]));+ _mm256_mask_storeu_epi32(&out[4 * sizeof(__m256i)], (__mmask8)-1, _mm512_castsi512_si256(padded[4]));+ _mm256_mask_storeu_epi32(&out[5 * sizeof(__m256i)], (__mmask8)-1, _mm512_castsi512_si256(padded[5]));+ _mm256_mask_storeu_epi32(&out[6 * sizeof(__m256i)], (__mmask8)-1, _mm512_castsi512_si256(padded[6]));+ _mm256_mask_storeu_epi32(&out[7 * sizeof(__m256i)], (__mmask8)-1, _mm512_castsi512_si256(padded[7]));+ _mm256_mask_storeu_epi32(&out[8 * sizeof(__m256i)], (__mmask8)-1, _mm512_castsi512_si256(padded[8]));+ _mm256_mask_storeu_epi32(&out[9 * sizeof(__m256i)], (__mmask8)-1, _mm512_castsi512_si256(padded[9]));+ _mm256_mask_storeu_epi32(&out[10 * sizeof(__m256i)], (__mmask8)-1, _mm512_castsi512_si256(padded[10]));+ _mm256_mask_storeu_epi32(&out[11 * sizeof(__m256i)], (__mmask8)-1, _mm512_castsi512_si256(padded[11]));+ _mm256_mask_storeu_epi32(&out[12 * sizeof(__m256i)], (__mmask8)-1, _mm512_castsi512_si256(padded[12]));+ _mm256_mask_storeu_epi32(&out[13 * sizeof(__m256i)], (__mmask8)-1, _mm512_castsi512_si256(padded[13]));+ _mm256_mask_storeu_epi32(&out[14 * sizeof(__m256i)], (__mmask8)-1, _mm512_castsi512_si256(padded[14]));+ _mm256_mask_storeu_epi32(&out[15 * sizeof(__m256i)], (__mmask8)-1, _mm512_castsi512_si256(padded[15]));+}++static+void blake3_xof16_avx512(const uint32_t cv[8],+ const uint8_t block[BLAKE3_BLOCK_LEN],+ uint8_t block_len, uint64_t counter, uint8_t flags,+ uint8_t out[16 * 64]) {+ __m512i h_vecs[8] = {+ set1_512(cv[0]), set1_512(cv[1]), set1_512(cv[2]), set1_512(cv[3]),+ set1_512(cv[4]), set1_512(cv[5]), set1_512(cv[6]), set1_512(cv[7]),+ };+ uint32_t block_words[16];+ load_block_words(block, block_words);+ __m512i msg_vecs[16];+ for (size_t i = 0; i < 16; i++) {+ msg_vecs[i] = set1_512(block_words[i]);+ }+ __m512i counter_low_vec, counter_high_vec;+ load_counters16(counter, true, &counter_low_vec, &counter_high_vec);+ __m512i block_len_vec = set1_512(block_len);+ __m512i block_flags_vec = set1_512(flags);+ __m512i v[16] = {+ h_vecs[0], h_vecs[1], h_vecs[2], h_vecs[3],+ h_vecs[4], h_vecs[5], h_vecs[6], h_vecs[7],+ set1_512(IV[0]), set1_512(IV[1]), set1_512(IV[2]), set1_512(IV[3]),+ counter_low_vec, counter_high_vec, block_len_vec, block_flags_vec,+ };+ round_fn16(v, msg_vecs, 0);+ round_fn16(v, msg_vecs, 1);+ round_fn16(v, msg_vecs, 2);+ round_fn16(v, msg_vecs, 3);+ round_fn16(v, msg_vecs, 4);+ round_fn16(v, msg_vecs, 5);+ round_fn16(v, msg_vecs, 6);+ for (size_t i = 0; i < 8; i++) {+ v[i] = xor_512(v[i], v[i+8]);+ v[i+8] = xor_512(v[i+8], h_vecs[i]);+ }+ transpose_vecs_512(&v[0]);+ for (size_t i = 0; i < 16; i++) {+ storeu_512(v[i], &out[i * sizeof(__m512i)]);+ }+}++/*+ * ----------------------------------------------------------------------------+ * hash_many_avx512+ * ----------------------------------------------------------------------------+ */++INLINE void hash_one_avx512(const uint8_t *input, size_t blocks,+ const uint32_t key[8], uint64_t counter,+ uint8_t flags, uint8_t flags_start,+ uint8_t flags_end, uint8_t out[BLAKE3_OUT_LEN]) {+ uint32_t cv[8];+ memcpy(cv, key, BLAKE3_KEY_LEN);+ uint8_t block_flags = flags | flags_start;+ while (blocks > 0) {+ if (blocks == 1) {+ block_flags |= flags_end;+ }+ blake3_compress_in_place_avx512(cv, input, BLAKE3_BLOCK_LEN, counter,+ block_flags);+ input = &input[BLAKE3_BLOCK_LEN];+ blocks -= 1;+ block_flags = flags;+ }+ memcpy(out, cv, BLAKE3_OUT_LEN);+}++void blake3_hash_many_avx512(const uint8_t *const *inputs, size_t num_inputs,+ size_t blocks, const uint32_t key[8],+ uint64_t counter, bool increment_counter,+ uint8_t flags, uint8_t flags_start,+ uint8_t flags_end, uint8_t *out) {+ while (num_inputs >= 16) {+ blake3_hash16_avx512(inputs, blocks, key, counter, increment_counter, flags,+ flags_start, flags_end, out);+ if (increment_counter) {+ counter += 16;+ }+ inputs += 16;+ num_inputs -= 16;+ out = &out[16 * BLAKE3_OUT_LEN];+ }+ while (num_inputs >= 8) {+ blake3_hash8_avx512(inputs, blocks, key, counter, increment_counter, flags,+ flags_start, flags_end, out);+ if (increment_counter) {+ counter += 8;+ }+ inputs += 8;+ num_inputs -= 8;+ out = &out[8 * BLAKE3_OUT_LEN];+ }+ while (num_inputs >= 4) {+ blake3_hash4_avx512(inputs, blocks, key, counter, increment_counter, flags,+ flags_start, flags_end, out);+ if (increment_counter) {+ counter += 4;+ }+ inputs += 4;+ num_inputs -= 4;+ out = &out[4 * BLAKE3_OUT_LEN];+ }+ while (num_inputs > 0) {+ hash_one_avx512(inputs[0], blocks, key, counter, flags, flags_start,+ flags_end, out);+ if (increment_counter) {+ counter += 1;+ }+ inputs += 1;+ num_inputs -= 1;+ out = &out[BLAKE3_OUT_LEN];+ }+}++void blake3_xof_many_avx512(const uint32_t cv[8],+ const uint8_t block[BLAKE3_BLOCK_LEN],+ uint8_t block_len, uint64_t counter, uint8_t flags,+ uint8_t* out, size_t outblocks) {+ while (outblocks >= 16) {+ blake3_xof16_avx512(cv, block, block_len, counter, flags, out);+ counter += 16;+ outblocks -= 16;+ out += 16 * BLAKE3_BLOCK_LEN;+ }+ while (outblocks >= 8) {+ blake3_xof8_avx512(cv, block, block_len, counter, flags, out);+ counter += 8;+ outblocks -= 8;+ out += 8 * BLAKE3_BLOCK_LEN;+ }+ while (outblocks >= 4) {+ blake3_xof4_avx512(cv, block, block_len, counter, flags, out);+ counter += 4;+ outblocks -= 4;+ out += 4 * BLAKE3_BLOCK_LEN;+ }+ while (outblocks > 0) {+ blake3_compress_xof_avx512(cv, block, block_len, counter, flags, out);+ counter += 1;+ outblocks -= 1;+ out += BLAKE3_BLOCK_LEN;+ }+}--- /dev/null+++ b/veins/src/crypto/blake3/blake3_dispatch.c@@ -0,0 +1,332 @@+#include <stdbool.h>+#include <stddef.h>+#include <stdint.h>++#include "blake3_impl.h"++#if defined(_MSC_VER)+#include <Windows.h>+#endif++#if defined(IS_X86)+#if defined(_MSC_VER)+#include <intrin.h>+#elif defined(__GNUC__)+#include <immintrin.h>+#else+#undef IS_X86 /* Unimplemented! */+#endif+#endif++#if !defined(BLAKE3_ATOMICS)+#if defined(__has_include)+#if __has_include(<stdatomic.h>) && !defined(_MSC_VER)+#define BLAKE3_ATOMICS 1+#else+#define BLAKE3_ATOMICS 0+#endif /* __has_include(<stdatomic.h>) && !defined(_MSC_VER) */+#else+#define BLAKE3_ATOMICS 0+#endif /* defined(__has_include) */+#endif /* BLAKE3_ATOMICS */++#if BLAKE3_ATOMICS+#define ATOMIC_INT _Atomic int+#define ATOMIC_LOAD(x) x+#define ATOMIC_STORE(x, y) x = y+#elif defined(_MSC_VER)+#define ATOMIC_INT LONG+#define ATOMIC_LOAD(x) InterlockedOr(&x, 0)+#define ATOMIC_STORE(x, y) InterlockedExchange(&x, y)+#else+#define ATOMIC_INT int+#define ATOMIC_LOAD(x) x+#define ATOMIC_STORE(x, y) x = y+#endif++#define MAYBE_UNUSED(x) (void)((x))++#if defined(IS_X86)+static uint64_t xgetbv(void) {+#if defined(_MSC_VER)+ return _xgetbv(0);+#else+ uint32_t eax = 0, edx = 0;+ __asm__ __volatile__("xgetbv\n" : "=a"(eax), "=d"(edx) : "c"(0));+ return ((uint64_t)edx << 32) | eax;+#endif+}++static void cpuid(uint32_t out[4], uint32_t id) {+#if defined(_MSC_VER)+ __cpuid((int *)out, id);+#elif defined(__i386__) || defined(_M_IX86)+ __asm__ __volatile__("movl %%ebx, %1\n"+ "cpuid\n"+ "xchgl %1, %%ebx\n"+ : "=a"(out[0]), "=r"(out[1]), "=c"(out[2]), "=d"(out[3])+ : "a"(id));+#else+ __asm__ __volatile__("cpuid\n"+ : "=a"(out[0]), "=b"(out[1]), "=c"(out[2]), "=d"(out[3])+ : "a"(id));+#endif+}++static void cpuidex(uint32_t out[4], uint32_t id, uint32_t sid) {+#if defined(_MSC_VER)+ __cpuidex((int *)out, id, sid);+#elif defined(__i386__) || defined(_M_IX86)+ __asm__ __volatile__("movl %%ebx, %1\n"+ "cpuid\n"+ "xchgl %1, %%ebx\n"+ : "=a"(out[0]), "=r"(out[1]), "=c"(out[2]), "=d"(out[3])+ : "a"(id), "c"(sid));+#else+ __asm__ __volatile__("cpuid\n"+ : "=a"(out[0]), "=b"(out[1]), "=c"(out[2]), "=d"(out[3])+ : "a"(id), "c"(sid));+#endif+}+++enum cpu_feature {+ SSE2 = 1 << 0,+ SSSE3 = 1 << 1,+ SSE41 = 1 << 2,+ AVX = 1 << 3,+ AVX2 = 1 << 4,+ AVX512F = 1 << 5,+ AVX512VL = 1 << 6,+ /* ... */+ UNDEFINED = 1 << 30+};++#if !defined(BLAKE3_TESTING)+static /* Allow the variable to be controlled manually for testing */+#endif+ ATOMIC_INT g_cpu_features = UNDEFINED;++#if !defined(BLAKE3_TESTING)+static+#endif+ enum cpu_feature+ get_cpu_features(void) {++ /* If TSAN detects a data race here, try compiling with -DBLAKE3_ATOMICS=1 */+ enum cpu_feature features = ATOMIC_LOAD(g_cpu_features);+ if (features != UNDEFINED) {+ return features;+ } else {+#if defined(IS_X86)+ uint32_t regs[4] = {0};+ uint32_t *eax = ®s[0], *ebx = ®s[1], *ecx = ®s[2], *edx = ®s[3];+ (void)edx;+ features = 0;+ cpuid(regs, 0);+ const int max_id = *eax;+ cpuid(regs, 1);+#if defined(__amd64__) || defined(_M_X64)+ features |= SSE2;+#else+ if (*edx & (1UL << 26))+ features |= SSE2;+#endif+ if (*ecx & (1UL << 9))+ features |= SSSE3;+ if (*ecx & (1UL << 19))+ features |= SSE41;++ if (*ecx & (1UL << 27)) { // OSXSAVE+ const uint64_t mask = xgetbv();+ if ((mask & 6) == 6) { // SSE and AVX states+ if (*ecx & (1UL << 28))+ features |= AVX;+ if (max_id >= 7) {+ cpuidex(regs, 7, 0);+ if (*ebx & (1UL << 5))+ features |= AVX2;+ if ((mask & 224) == 224) { // Opmask, ZMM_Hi256, Hi16_Zmm+ if (*ebx & (1UL << 31))+ features |= AVX512VL;+ if (*ebx & (1UL << 16))+ features |= AVX512F;+ }+ }+ }+ }+ ATOMIC_STORE(g_cpu_features, features);+ return features;+#else+ /* How to detect NEON? */+ return 0;+#endif+ }+}+#endif++void blake3_compress_in_place(uint32_t cv[8],+ const uint8_t block[BLAKE3_BLOCK_LEN],+ uint8_t block_len, uint64_t counter,+ uint8_t flags) {+#if defined(IS_X86)+ const enum cpu_feature features = get_cpu_features();+ MAYBE_UNUSED(features);+#if !defined(BLAKE3_NO_AVX512)+ if (features & AVX512VL) {+ blake3_compress_in_place_avx512(cv, block, block_len, counter, flags);+ return;+ }+#endif+#if !defined(BLAKE3_NO_SSE41)+ if (features & SSE41) {+ blake3_compress_in_place_sse41(cv, block, block_len, counter, flags);+ return;+ }+#endif+#if !defined(BLAKE3_NO_SSE2)+ if (features & SSE2) {+ blake3_compress_in_place_sse2(cv, block, block_len, counter, flags);+ return;+ }+#endif+#endif+ blake3_compress_in_place_portable(cv, block, block_len, counter, flags);+}++void blake3_compress_xof(const uint32_t cv[8],+ const uint8_t block[BLAKE3_BLOCK_LEN],+ uint8_t block_len, uint64_t counter, uint8_t flags,+ uint8_t out[64]) {+#if defined(IS_X86)+ const enum cpu_feature features = get_cpu_features();+ MAYBE_UNUSED(features);+#if !defined(BLAKE3_NO_AVX512)+ if (features & AVX512VL) {+ blake3_compress_xof_avx512(cv, block, block_len, counter, flags, out);+ return;+ }+#endif+#if !defined(BLAKE3_NO_SSE41)+ if (features & SSE41) {+ blake3_compress_xof_sse41(cv, block, block_len, counter, flags, out);+ return;+ }+#endif+#if !defined(BLAKE3_NO_SSE2)+ if (features & SSE2) {+ blake3_compress_xof_sse2(cv, block, block_len, counter, flags, out);+ return;+ }+#endif+#endif+ blake3_compress_xof_portable(cv, block, block_len, counter, flags, out);+}+++void blake3_xof_many(const uint32_t cv[8],+ const uint8_t block[BLAKE3_BLOCK_LEN],+ uint8_t block_len, uint64_t counter, uint8_t flags,+ uint8_t out[64], size_t outblocks) {+ if (outblocks == 0) {+ // The current assembly implementation always outputs at least 1 block.+ return;+ }+#if defined(IS_X86)+ const enum cpu_feature features = get_cpu_features();+ MAYBE_UNUSED(features);+#if !defined(_WIN32) && !defined(__CYGWIN__) && !defined(BLAKE3_NO_AVX512)+ if (features & AVX512VL) {+ blake3_xof_many_avx512(cv, block, block_len, counter, flags, out, outblocks);+ return;+ }+#endif+#endif+ for(size_t i = 0; i < outblocks; ++i) {+ blake3_compress_xof(cv, block, block_len, counter + i, flags, out + 64*i);+ }+}++void blake3_hash_many(const uint8_t *const *inputs, size_t num_inputs,+ size_t blocks, const uint32_t key[8], uint64_t counter,+ bool increment_counter, uint8_t flags,+ uint8_t flags_start, uint8_t flags_end, uint8_t *out) {+#if defined(IS_X86)+ const enum cpu_feature features = get_cpu_features();+ MAYBE_UNUSED(features);+#if !defined(BLAKE3_NO_AVX512)+ if ((features & (AVX512F|AVX512VL)) == (AVX512F|AVX512VL)) {+ blake3_hash_many_avx512(inputs, num_inputs, blocks, key, counter,+ increment_counter, flags, flags_start, flags_end,+ out);+ return;+ }+#endif+#if !defined(BLAKE3_NO_AVX2)+ if (features & AVX2) {+ blake3_hash_many_avx2(inputs, num_inputs, blocks, key, counter,+ increment_counter, flags, flags_start, flags_end,+ out);+ return;+ }+#endif+#if !defined(BLAKE3_NO_SSE41)+ if (features & SSE41) {+ blake3_hash_many_sse41(inputs, num_inputs, blocks, key, counter,+ increment_counter, flags, flags_start, flags_end,+ out);+ return;+ }+#endif+#if !defined(BLAKE3_NO_SSE2)+ if (features & SSE2) {+ blake3_hash_many_sse2(inputs, num_inputs, blocks, key, counter,+ increment_counter, flags, flags_start, flags_end,+ out);+ return;+ }+#endif+#endif++#if BLAKE3_USE_NEON == 1+ blake3_hash_many_neon(inputs, num_inputs, blocks, key, counter,+ increment_counter, flags, flags_start, flags_end, out);+ return;+#endif++ blake3_hash_many_portable(inputs, num_inputs, blocks, key, counter,+ increment_counter, flags, flags_start, flags_end,+ out);+}++// The dynamically detected SIMD degree of the current platform.+size_t blake3_simd_degree(void) {+#if defined(IS_X86)+ const enum cpu_feature features = get_cpu_features();+ MAYBE_UNUSED(features);+#if !defined(BLAKE3_NO_AVX512)+ if ((features & (AVX512F|AVX512VL)) == (AVX512F|AVX512VL)) {+ return 16;+ }+#endif+#if !defined(BLAKE3_NO_AVX2)+ if (features & AVX2) {+ return 8;+ }+#endif+#if !defined(BLAKE3_NO_SSE41)+ if (features & SSE41) {+ return 4;+ }+#endif+#if !defined(BLAKE3_NO_SSE2)+ if (features & SSE2) {+ return 4;+ }+#endif+#endif+#if BLAKE3_USE_NEON == 1+ return 4;+#endif+ return 1;+}--- /dev/null+++ b/veins/src/crypto/blake3/blake3_impl.h@@ -0,0 +1,333 @@+#ifndef BLAKE3_IMPL_H+#define BLAKE3_IMPL_H++#include <assert.h>+#include <stdbool.h>+#include <stddef.h>+#include <stdint.h>+#include <string.h>++#include "blake3.h"++#ifdef __cplusplus+extern "C" {+#endif++// internal flags+enum blake3_flags {+ CHUNK_START = 1 << 0,+ CHUNK_END = 1 << 1,+ PARENT = 1 << 2,+ ROOT = 1 << 3,+ KEYED_HASH = 1 << 4,+ DERIVE_KEY_CONTEXT = 1 << 5,+ DERIVE_KEY_MATERIAL = 1 << 6,+};++// This C implementation tries to support recent versions of GCC, Clang, and+// MSVC.+#if defined(_MSC_VER)+#define INLINE static __forceinline+#else+#define INLINE static inline __attribute__((always_inline))+#endif++#ifdef __cplusplus+#define NOEXCEPT noexcept+#else+#define NOEXCEPT+#endif++#if (defined(__x86_64__) || defined(_M_X64)) && !defined(_M_ARM64EC)+#define IS_X86+#define IS_X86_64+#endif++#if defined(__i386__) || defined(_M_IX86)+#define IS_X86+#define IS_X86_32+#endif++#if defined(__aarch64__) || defined(_M_ARM64) || defined(_M_ARM64EC)+#define IS_AARCH64+#endif++#if defined(IS_X86)+#if defined(_MSC_VER)+#include <intrin.h>+#endif+#endif++#if !defined(BLAKE3_USE_NEON) + // If BLAKE3_USE_NEON not manually set, autodetect based on AArch64ness+ #if defined(IS_AARCH64)+ #if defined(__ARM_BIG_ENDIAN)+ #define BLAKE3_USE_NEON 0+ #else+ #define BLAKE3_USE_NEON 1+ #endif+ #else+ #define BLAKE3_USE_NEON 0+ #endif+#endif++#if defined(IS_X86)+#define MAX_SIMD_DEGREE 16+#elif BLAKE3_USE_NEON == 1+#define MAX_SIMD_DEGREE 4+#else+#define MAX_SIMD_DEGREE 1+#endif++// There are some places where we want a static size that's equal to the+// MAX_SIMD_DEGREE, but also at least 2.+#define MAX_SIMD_DEGREE_OR_2 (MAX_SIMD_DEGREE > 2 ? MAX_SIMD_DEGREE : 2)++static const uint32_t IV[8] = {0x6A09E667UL, 0xBB67AE85UL, 0x3C6EF372UL,+ 0xA54FF53AUL, 0x510E527FUL, 0x9B05688CUL,+ 0x1F83D9ABUL, 0x5BE0CD19UL};++static const uint8_t MSG_SCHEDULE[7][16] = {+ {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},+};++/* Find index of the highest set bit */+/* x is assumed to be nonzero. */+static unsigned int highest_one(uint64_t x) {+#if defined(__GNUC__) || defined(__clang__)+ return 63 ^ (unsigned int)__builtin_clzll(x);+#elif defined(_MSC_VER) && defined(IS_X86_64)+ unsigned long index;+ _BitScanReverse64(&index, x);+ return index;+#elif defined(_MSC_VER) && defined(IS_X86_32)+ if(x >> 32) {+ unsigned long index;+ _BitScanReverse(&index, (unsigned long)(x >> 32));+ return 32 + index;+ } else {+ unsigned long index;+ _BitScanReverse(&index, (unsigned long)x);+ return index;+ }+#else+ unsigned int c = 0;+ if(x & 0xffffffff00000000ULL) { x >>= 32; c += 32; }+ if(x & 0x00000000ffff0000ULL) { x >>= 16; c += 16; }+ if(x & 0x000000000000ff00ULL) { x >>= 8; c += 8; }+ if(x & 0x00000000000000f0ULL) { x >>= 4; c += 4; }+ if(x & 0x000000000000000cULL) { x >>= 2; c += 2; }+ if(x & 0x0000000000000002ULL) { c += 1; }+ return c;+#endif+}++// Count the number of 1 bits.+INLINE unsigned int popcnt(uint64_t x) {+#if defined(__GNUC__) || defined(__clang__)+ return (unsigned int)__builtin_popcountll(x);+#else+ unsigned int count = 0;+ while (x != 0) {+ count += 1;+ x &= x - 1;+ }+ return count;+#endif+}++// Largest power of two less than or equal to x. As a special case, returns 1+// when x is 0. +INLINE uint64_t round_down_to_power_of_2(uint64_t x) {+ return 1ULL << highest_one(x | 1);+}++INLINE uint32_t counter_low(uint64_t counter) { return (uint32_t)counter; }++INLINE uint32_t counter_high(uint64_t counter) {+ return (uint32_t)(counter >> 32);+}++INLINE uint32_t load32(const void *src) {+ const uint8_t *p = (const uint8_t *)src;+ return ((uint32_t)(p[0]) << 0) | ((uint32_t)(p[1]) << 8) |+ ((uint32_t)(p[2]) << 16) | ((uint32_t)(p[3]) << 24);+}++INLINE void load_key_words(const uint8_t key[BLAKE3_KEY_LEN],+ uint32_t key_words[8]) {+ key_words[0] = load32(&key[0 * 4]);+ key_words[1] = load32(&key[1 * 4]);+ key_words[2] = load32(&key[2 * 4]);+ key_words[3] = load32(&key[3 * 4]);+ key_words[4] = load32(&key[4 * 4]);+ key_words[5] = load32(&key[5 * 4]);+ key_words[6] = load32(&key[6 * 4]);+ key_words[7] = load32(&key[7 * 4]);+}++INLINE void load_block_words(const uint8_t block[BLAKE3_BLOCK_LEN],+ uint32_t block_words[16]) {+ for (size_t i = 0; i < 16; i++) {+ block_words[i] = load32(&block[i * 4]);+ }+}++INLINE void store32(void *dst, uint32_t w) {+ uint8_t *p = (uint8_t *)dst;+ p[0] = (uint8_t)(w >> 0);+ p[1] = (uint8_t)(w >> 8);+ p[2] = (uint8_t)(w >> 16);+ p[3] = (uint8_t)(w >> 24);+}++INLINE void store_cv_words(uint8_t bytes_out[32], uint32_t cv_words[8]) {+ store32(&bytes_out[0 * 4], cv_words[0]);+ store32(&bytes_out[1 * 4], cv_words[1]);+ store32(&bytes_out[2 * 4], cv_words[2]);+ store32(&bytes_out[3 * 4], cv_words[3]);+ store32(&bytes_out[4 * 4], cv_words[4]);+ store32(&bytes_out[5 * 4], cv_words[5]);+ store32(&bytes_out[6 * 4], cv_words[6]);+ store32(&bytes_out[7 * 4], cv_words[7]);+}++void blake3_compress_in_place(uint32_t cv[8],+ const uint8_t block[BLAKE3_BLOCK_LEN],+ uint8_t block_len, uint64_t counter,+ uint8_t flags);++void blake3_compress_xof(const uint32_t cv[8],+ const uint8_t block[BLAKE3_BLOCK_LEN],+ uint8_t block_len, uint64_t counter, uint8_t flags,+ uint8_t out[64]);++void blake3_xof_many(const uint32_t cv[8],+ const uint8_t block[BLAKE3_BLOCK_LEN],+ uint8_t block_len, uint64_t counter, uint8_t flags,+ uint8_t out[64], size_t outblocks);++void blake3_hash_many(const uint8_t *const *inputs, size_t num_inputs,+ size_t blocks, const uint32_t key[8], uint64_t counter,+ bool increment_counter, uint8_t flags,+ uint8_t flags_start, uint8_t flags_end, uint8_t *out);++size_t blake3_simd_degree(void);++BLAKE3_PRIVATE size_t blake3_compress_subtree_wide(const uint8_t *input, size_t input_len,+ const uint32_t key[8],+ uint64_t chunk_counter, uint8_t flags,+ uint8_t *out, bool use_tbb);++#if defined(BLAKE3_USE_TBB)+BLAKE3_PRIVATE void blake3_compress_subtree_wide_join_tbb(+ // shared params+ const uint32_t key[8], uint8_t flags, bool use_tbb,+ // left-hand side params+ const uint8_t *l_input, size_t l_input_len, uint64_t l_chunk_counter,+ uint8_t *l_cvs, size_t *l_n,+ // right-hand side params+ const uint8_t *r_input, size_t r_input_len, uint64_t r_chunk_counter,+ uint8_t *r_cvs, size_t *r_n) NOEXCEPT;+#endif++// Declarations for implementation-specific functions.+void blake3_compress_in_place_portable(uint32_t cv[8],+ const uint8_t block[BLAKE3_BLOCK_LEN],+ uint8_t block_len, uint64_t counter,+ uint8_t flags);++void blake3_compress_xof_portable(const uint32_t cv[8],+ const uint8_t block[BLAKE3_BLOCK_LEN],+ uint8_t block_len, uint64_t counter,+ uint8_t flags, uint8_t out[64]);++void blake3_hash_many_portable(const uint8_t *const *inputs, size_t num_inputs,+ size_t blocks, const uint32_t key[8],+ uint64_t counter, bool increment_counter,+ uint8_t flags, uint8_t flags_start,+ uint8_t flags_end, uint8_t *out);++#if defined(IS_X86)+#if !defined(BLAKE3_NO_SSE2)+void blake3_compress_in_place_sse2(uint32_t cv[8],+ const uint8_t block[BLAKE3_BLOCK_LEN],+ uint8_t block_len, uint64_t counter,+ uint8_t flags);+void blake3_compress_xof_sse2(const uint32_t cv[8],+ const uint8_t block[BLAKE3_BLOCK_LEN],+ uint8_t block_len, uint64_t counter,+ uint8_t flags, uint8_t out[64]);+void blake3_hash_many_sse2(const uint8_t *const *inputs, size_t num_inputs,+ size_t blocks, const uint32_t key[8],+ uint64_t counter, bool increment_counter,+ uint8_t flags, uint8_t flags_start,+ uint8_t flags_end, uint8_t *out);+#endif+#if !defined(BLAKE3_NO_SSE41)+void blake3_compress_in_place_sse41(uint32_t cv[8],+ const uint8_t block[BLAKE3_BLOCK_LEN],+ uint8_t block_len, uint64_t counter,+ uint8_t flags);+void blake3_compress_xof_sse41(const uint32_t cv[8],+ const uint8_t block[BLAKE3_BLOCK_LEN],+ uint8_t block_len, uint64_t counter,+ uint8_t flags, uint8_t out[64]);+void blake3_hash_many_sse41(const uint8_t *const *inputs, size_t num_inputs,+ size_t blocks, const uint32_t key[8],+ uint64_t counter, bool increment_counter,+ uint8_t flags, uint8_t flags_start,+ uint8_t flags_end, uint8_t *out);+#endif+#if !defined(BLAKE3_NO_AVX2)+void blake3_hash_many_avx2(const uint8_t *const *inputs, size_t num_inputs,+ size_t blocks, const uint32_t key[8],+ uint64_t counter, bool increment_counter,+ uint8_t flags, uint8_t flags_start,+ uint8_t flags_end, uint8_t *out);+#endif+#if !defined(BLAKE3_NO_AVX512)+void blake3_compress_in_place_avx512(uint32_t cv[8],+ const uint8_t block[BLAKE3_BLOCK_LEN],+ uint8_t block_len, uint64_t counter,+ uint8_t flags);++void blake3_compress_xof_avx512(const uint32_t cv[8],+ const uint8_t block[BLAKE3_BLOCK_LEN],+ uint8_t block_len, uint64_t counter,+ uint8_t flags, uint8_t out[64]);++void blake3_hash_many_avx512(const uint8_t *const *inputs, size_t num_inputs,+ size_t blocks, const uint32_t key[8],+ uint64_t counter, bool increment_counter,+ uint8_t flags, uint8_t flags_start,+ uint8_t flags_end, uint8_t *out);++#if !defined(_WIN32) && !defined(__CYGWIN__)+void blake3_xof_many_avx512(const uint32_t cv[8],+ const uint8_t block[BLAKE3_BLOCK_LEN],+ uint8_t block_len, uint64_t counter, uint8_t flags,+ uint8_t* out, size_t outblocks);+#endif+#endif+#endif++#if BLAKE3_USE_NEON == 1+void blake3_hash_many_neon(const uint8_t *const *inputs, size_t num_inputs,+ size_t blocks, const uint32_t key[8],+ uint64_t counter, bool increment_counter,+ uint8_t flags, uint8_t flags_start,+ uint8_t flags_end, uint8_t *out);+#endif++#ifdef __cplusplus+}+#endif++#endif /* BLAKE3_IMPL_H */--- /dev/null+++ b/veins/src/crypto/blake3/blake3_portable.c@@ -0,0 +1,160 @@+#include "blake3_impl.h"+#include <string.h>++INLINE uint32_t rotr32(uint32_t w, uint32_t c) {+ return (w >> c) | (w << (32 - c));+}++INLINE void g(uint32_t *state, size_t a, size_t b, size_t c, size_t d,+ uint32_t x, uint32_t y) {+ state[a] = state[a] + state[b] + x;+ state[d] = rotr32(state[d] ^ state[a], 16);+ state[c] = state[c] + state[d];+ state[b] = rotr32(state[b] ^ state[c], 12);+ state[a] = state[a] + state[b] + y;+ state[d] = rotr32(state[d] ^ state[a], 8);+ state[c] = state[c] + state[d];+ state[b] = rotr32(state[b] ^ state[c], 7);+}++INLINE void round_fn(uint32_t state[16], const uint32_t *msg, size_t round) {+ // Select the message schedule based on the round.+ const uint8_t *schedule = MSG_SCHEDULE[round];++ // Mix the columns.+ g(state, 0, 4, 8, 12, msg[schedule[0]], msg[schedule[1]]);+ g(state, 1, 5, 9, 13, msg[schedule[2]], msg[schedule[3]]);+ g(state, 2, 6, 10, 14, msg[schedule[4]], msg[schedule[5]]);+ g(state, 3, 7, 11, 15, msg[schedule[6]], msg[schedule[7]]);++ // Mix the rows.+ g(state, 0, 5, 10, 15, msg[schedule[8]], msg[schedule[9]]);+ g(state, 1, 6, 11, 12, msg[schedule[10]], msg[schedule[11]]);+ g(state, 2, 7, 8, 13, msg[schedule[12]], msg[schedule[13]]);+ g(state, 3, 4, 9, 14, msg[schedule[14]], msg[schedule[15]]);+}++INLINE void compress_pre(uint32_t state[16], const uint32_t cv[8],+ const uint8_t block[BLAKE3_BLOCK_LEN],+ uint8_t block_len, uint64_t counter, uint8_t flags) {+ uint32_t block_words[16];+ block_words[0] = load32(block + 4 * 0);+ block_words[1] = load32(block + 4 * 1);+ block_words[2] = load32(block + 4 * 2);+ block_words[3] = load32(block + 4 * 3);+ block_words[4] = load32(block + 4 * 4);+ block_words[5] = load32(block + 4 * 5);+ block_words[6] = load32(block + 4 * 6);+ block_words[7] = load32(block + 4 * 7);+ block_words[8] = load32(block + 4 * 8);+ block_words[9] = load32(block + 4 * 9);+ block_words[10] = load32(block + 4 * 10);+ block_words[11] = load32(block + 4 * 11);+ block_words[12] = load32(block + 4 * 12);+ block_words[13] = load32(block + 4 * 13);+ block_words[14] = load32(block + 4 * 14);+ block_words[15] = load32(block + 4 * 15);++ state[0] = cv[0];+ state[1] = cv[1];+ state[2] = cv[2];+ state[3] = cv[3];+ state[4] = cv[4];+ state[5] = cv[5];+ state[6] = cv[6];+ state[7] = cv[7];+ state[8] = IV[0];+ state[9] = IV[1];+ state[10] = IV[2];+ state[11] = IV[3];+ state[12] = counter_low(counter);+ state[13] = counter_high(counter);+ state[14] = (uint32_t)block_len;+ state[15] = (uint32_t)flags;++ round_fn(state, &block_words[0], 0);+ round_fn(state, &block_words[0], 1);+ round_fn(state, &block_words[0], 2);+ round_fn(state, &block_words[0], 3);+ round_fn(state, &block_words[0], 4);+ round_fn(state, &block_words[0], 5);+ round_fn(state, &block_words[0], 6);+}++void blake3_compress_in_place_portable(uint32_t cv[8],+ const uint8_t block[BLAKE3_BLOCK_LEN],+ uint8_t block_len, uint64_t counter,+ uint8_t flags) {+ uint32_t state[16];+ compress_pre(state, cv, block, block_len, counter, flags);+ cv[0] = state[0] ^ state[8];+ cv[1] = state[1] ^ state[9];+ cv[2] = state[2] ^ state[10];+ cv[3] = state[3] ^ state[11];+ cv[4] = state[4] ^ state[12];+ cv[5] = state[5] ^ state[13];+ cv[6] = state[6] ^ state[14];+ cv[7] = state[7] ^ state[15];+}++void blake3_compress_xof_portable(const uint32_t cv[8],+ const uint8_t block[BLAKE3_BLOCK_LEN],+ uint8_t block_len, uint64_t counter,+ uint8_t flags, uint8_t out[64]) {+ uint32_t state[16];+ compress_pre(state, cv, block, block_len, counter, flags);++ store32(&out[0 * 4], state[0] ^ state[8]);+ store32(&out[1 * 4], state[1] ^ state[9]);+ store32(&out[2 * 4], state[2] ^ state[10]);+ store32(&out[3 * 4], state[3] ^ state[11]);+ store32(&out[4 * 4], state[4] ^ state[12]);+ store32(&out[5 * 4], state[5] ^ state[13]);+ store32(&out[6 * 4], state[6] ^ state[14]);+ store32(&out[7 * 4], state[7] ^ state[15]);+ store32(&out[8 * 4], state[8] ^ cv[0]);+ store32(&out[9 * 4], state[9] ^ cv[1]);+ store32(&out[10 * 4], state[10] ^ cv[2]);+ store32(&out[11 * 4], state[11] ^ cv[3]);+ store32(&out[12 * 4], state[12] ^ cv[4]);+ store32(&out[13 * 4], state[13] ^ cv[5]);+ store32(&out[14 * 4], state[14] ^ cv[6]);+ store32(&out[15 * 4], state[15] ^ cv[7]);+}++INLINE void hash_one_portable(const uint8_t *input, size_t blocks,+ const uint32_t key[8], uint64_t counter,+ uint8_t flags, uint8_t flags_start,+ uint8_t flags_end, uint8_t out[BLAKE3_OUT_LEN]) {+ uint32_t cv[8];+ memcpy(cv, key, BLAKE3_KEY_LEN);+ uint8_t block_flags = flags | flags_start;+ while (blocks > 0) {+ if (blocks == 1) {+ block_flags |= flags_end;+ }+ blake3_compress_in_place_portable(cv, input, BLAKE3_BLOCK_LEN, counter,+ block_flags);+ input = &input[BLAKE3_BLOCK_LEN];+ blocks -= 1;+ block_flags = flags;+ }+ store_cv_words(out, cv);+}++void blake3_hash_many_portable(const uint8_t *const *inputs, size_t num_inputs,+ size_t blocks, const uint32_t key[8],+ uint64_t counter, bool increment_counter,+ uint8_t flags, uint8_t flags_start,+ uint8_t flags_end, uint8_t *out) {+ while (num_inputs > 0) {+ hash_one_portable(inputs[0], blocks, key, counter, flags, flags_start,+ flags_end, out);+ if (increment_counter) {+ counter += 1;+ }+ inputs += 1;+ num_inputs -= 1;+ out = &out[BLAKE3_OUT_LEN];+ }+}--- /dev/null+++ b/veins/src/crypto/blake3/blake3_sse2.c@@ -0,0 +1,566 @@+#include "blake3_impl.h"++#include <immintrin.h>++#define DEGREE 4++#define _mm_shuffle_ps2(a, b, c) \+ (_mm_castps_si128( \+ _mm_shuffle_ps(_mm_castsi128_ps(a), _mm_castsi128_ps(b), (c))))++INLINE __m128i loadu(const uint8_t src[16]) {+ return _mm_loadu_si128((const __m128i *)src);+}++INLINE void storeu(__m128i src, uint8_t dest[16]) {+ _mm_storeu_si128((__m128i *)dest, src);+}++INLINE __m128i addv(__m128i a, __m128i b) { return _mm_add_epi32(a, b); }++// Note that clang-format doesn't like the name "xor" for some reason.+INLINE __m128i xorv(__m128i a, __m128i b) { return _mm_xor_si128(a, b); }++INLINE __m128i set1(uint32_t x) { return _mm_set1_epi32((int32_t)x); }++INLINE __m128i set4(uint32_t a, uint32_t b, uint32_t c, uint32_t d) {+ return _mm_setr_epi32((int32_t)a, (int32_t)b, (int32_t)c, (int32_t)d);+}++INLINE __m128i rot16(__m128i x) {+ return _mm_shufflehi_epi16(_mm_shufflelo_epi16(x, 0xB1), 0xB1);+}++INLINE __m128i rot12(__m128i x) {+ return xorv(_mm_srli_epi32(x, 12), _mm_slli_epi32(x, 32 - 12));+}++INLINE __m128i rot8(__m128i x) {+ return xorv(_mm_srli_epi32(x, 8), _mm_slli_epi32(x, 32 - 8));+}++INLINE __m128i rot7(__m128i x) {+ return xorv(_mm_srli_epi32(x, 7), _mm_slli_epi32(x, 32 - 7));+}++INLINE void g1(__m128i *row0, __m128i *row1, __m128i *row2, __m128i *row3,+ __m128i m) {+ *row0 = addv(addv(*row0, m), *row1);+ *row3 = xorv(*row3, *row0);+ *row3 = rot16(*row3);+ *row2 = addv(*row2, *row3);+ *row1 = xorv(*row1, *row2);+ *row1 = rot12(*row1);+}++INLINE void g2(__m128i *row0, __m128i *row1, __m128i *row2, __m128i *row3,+ __m128i m) {+ *row0 = addv(addv(*row0, m), *row1);+ *row3 = xorv(*row3, *row0);+ *row3 = rot8(*row3);+ *row2 = addv(*row2, *row3);+ *row1 = xorv(*row1, *row2);+ *row1 = rot7(*row1);+}++// Note the optimization here of leaving row1 as the unrotated row, rather than+// row0. All the message loads below are adjusted to compensate for this. See+// discussion at https://github.com/sneves/blake2-avx2/pull/4+INLINE void diagonalize(__m128i *row0, __m128i *row2, __m128i *row3) {+ *row0 = _mm_shuffle_epi32(*row0, _MM_SHUFFLE(2, 1, 0, 3));+ *row3 = _mm_shuffle_epi32(*row3, _MM_SHUFFLE(1, 0, 3, 2));+ *row2 = _mm_shuffle_epi32(*row2, _MM_SHUFFLE(0, 3, 2, 1));+}++INLINE void undiagonalize(__m128i *row0, __m128i *row2, __m128i *row3) {+ *row0 = _mm_shuffle_epi32(*row0, _MM_SHUFFLE(0, 3, 2, 1));+ *row3 = _mm_shuffle_epi32(*row3, _MM_SHUFFLE(1, 0, 3, 2));+ *row2 = _mm_shuffle_epi32(*row2, _MM_SHUFFLE(2, 1, 0, 3));+}++INLINE __m128i blend_epi16(__m128i a, __m128i b, const int16_t imm8) {+ const __m128i bits = _mm_set_epi16(0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01);+ __m128i mask = _mm_set1_epi16(imm8);+ mask = _mm_and_si128(mask, bits);+ mask = _mm_cmpeq_epi16(mask, bits);+ return _mm_or_si128(_mm_and_si128(mask, b), _mm_andnot_si128(mask, a));+}++INLINE void compress_pre(__m128i rows[4], const uint32_t cv[8],+ const uint8_t block[BLAKE3_BLOCK_LEN],+ uint8_t block_len, uint64_t counter, uint8_t flags) {+ rows[0] = loadu((uint8_t *)&cv[0]);+ rows[1] = loadu((uint8_t *)&cv[4]);+ rows[2] = set4(IV[0], IV[1], IV[2], IV[3]);+ rows[3] = set4(counter_low(counter), counter_high(counter),+ (uint32_t)block_len, (uint32_t)flags);++ __m128i m0 = loadu(&block[sizeof(__m128i) * 0]);+ __m128i m1 = loadu(&block[sizeof(__m128i) * 1]);+ __m128i m2 = loadu(&block[sizeof(__m128i) * 2]);+ __m128i m3 = loadu(&block[sizeof(__m128i) * 3]);++ __m128i t0, t1, t2, t3, tt;++ // Round 1. The first round permutes the message words from the original+ // input order, into the groups that get mixed in parallel.+ t0 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(2, 0, 2, 0)); // 6 4 2 0+ g1(&rows[0], &rows[1], &rows[2], &rows[3], t0);+ t1 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(3, 1, 3, 1)); // 7 5 3 1+ g2(&rows[0], &rows[1], &rows[2], &rows[3], t1);+ diagonalize(&rows[0], &rows[2], &rows[3]);+ t2 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(2, 0, 2, 0)); // 14 12 10 8+ t2 = _mm_shuffle_epi32(t2, _MM_SHUFFLE(2, 1, 0, 3)); // 12 10 8 14+ g1(&rows[0], &rows[1], &rows[2], &rows[3], t2);+ t3 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(3, 1, 3, 1)); // 15 13 11 9+ t3 = _mm_shuffle_epi32(t3, _MM_SHUFFLE(2, 1, 0, 3)); // 13 11 9 15+ g2(&rows[0], &rows[1], &rows[2], &rows[3], t3);+ undiagonalize(&rows[0], &rows[2], &rows[3]);+ m0 = t0;+ m1 = t1;+ m2 = t2;+ m3 = t3;++ // Round 2. This round and all following rounds apply a fixed permutation+ // to the message words from the round before.+ t0 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(3, 1, 1, 2));+ t0 = _mm_shuffle_epi32(t0, _MM_SHUFFLE(0, 3, 2, 1));+ g1(&rows[0], &rows[1], &rows[2], &rows[3], t0);+ t1 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(3, 3, 2, 2));+ tt = _mm_shuffle_epi32(m0, _MM_SHUFFLE(0, 0, 3, 3));+ t1 = blend_epi16(tt, t1, 0xCC);+ g2(&rows[0], &rows[1], &rows[2], &rows[3], t1);+ diagonalize(&rows[0], &rows[2], &rows[3]);+ t2 = _mm_unpacklo_epi64(m3, m1);+ tt = blend_epi16(t2, m2, 0xC0);+ t2 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(1, 3, 2, 0));+ g1(&rows[0], &rows[1], &rows[2], &rows[3], t2);+ t3 = _mm_unpackhi_epi32(m1, m3);+ tt = _mm_unpacklo_epi32(m2, t3);+ t3 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(0, 1, 3, 2));+ g2(&rows[0], &rows[1], &rows[2], &rows[3], t3);+ undiagonalize(&rows[0], &rows[2], &rows[3]);+ m0 = t0;+ m1 = t1;+ m2 = t2;+ m3 = t3;++ // Round 3+ t0 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(3, 1, 1, 2));+ t0 = _mm_shuffle_epi32(t0, _MM_SHUFFLE(0, 3, 2, 1));+ g1(&rows[0], &rows[1], &rows[2], &rows[3], t0);+ t1 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(3, 3, 2, 2));+ tt = _mm_shuffle_epi32(m0, _MM_SHUFFLE(0, 0, 3, 3));+ t1 = blend_epi16(tt, t1, 0xCC);+ g2(&rows[0], &rows[1], &rows[2], &rows[3], t1);+ diagonalize(&rows[0], &rows[2], &rows[3]);+ t2 = _mm_unpacklo_epi64(m3, m1);+ tt = blend_epi16(t2, m2, 0xC0);+ t2 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(1, 3, 2, 0));+ g1(&rows[0], &rows[1], &rows[2], &rows[3], t2);+ t3 = _mm_unpackhi_epi32(m1, m3);+ tt = _mm_unpacklo_epi32(m2, t3);+ t3 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(0, 1, 3, 2));+ g2(&rows[0], &rows[1], &rows[2], &rows[3], t3);+ undiagonalize(&rows[0], &rows[2], &rows[3]);+ m0 = t0;+ m1 = t1;+ m2 = t2;+ m3 = t3;++ // Round 4+ t0 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(3, 1, 1, 2));+ t0 = _mm_shuffle_epi32(t0, _MM_SHUFFLE(0, 3, 2, 1));+ g1(&rows[0], &rows[1], &rows[2], &rows[3], t0);+ t1 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(3, 3, 2, 2));+ tt = _mm_shuffle_epi32(m0, _MM_SHUFFLE(0, 0, 3, 3));+ t1 = blend_epi16(tt, t1, 0xCC);+ g2(&rows[0], &rows[1], &rows[2], &rows[3], t1);+ diagonalize(&rows[0], &rows[2], &rows[3]);+ t2 = _mm_unpacklo_epi64(m3, m1);+ tt = blend_epi16(t2, m2, 0xC0);+ t2 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(1, 3, 2, 0));+ g1(&rows[0], &rows[1], &rows[2], &rows[3], t2);+ t3 = _mm_unpackhi_epi32(m1, m3);+ tt = _mm_unpacklo_epi32(m2, t3);+ t3 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(0, 1, 3, 2));+ g2(&rows[0], &rows[1], &rows[2], &rows[3], t3);+ undiagonalize(&rows[0], &rows[2], &rows[3]);+ m0 = t0;+ m1 = t1;+ m2 = t2;+ m3 = t3;++ // Round 5+ t0 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(3, 1, 1, 2));+ t0 = _mm_shuffle_epi32(t0, _MM_SHUFFLE(0, 3, 2, 1));+ g1(&rows[0], &rows[1], &rows[2], &rows[3], t0);+ t1 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(3, 3, 2, 2));+ tt = _mm_shuffle_epi32(m0, _MM_SHUFFLE(0, 0, 3, 3));+ t1 = blend_epi16(tt, t1, 0xCC);+ g2(&rows[0], &rows[1], &rows[2], &rows[3], t1);+ diagonalize(&rows[0], &rows[2], &rows[3]);+ t2 = _mm_unpacklo_epi64(m3, m1);+ tt = blend_epi16(t2, m2, 0xC0);+ t2 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(1, 3, 2, 0));+ g1(&rows[0], &rows[1], &rows[2], &rows[3], t2);+ t3 = _mm_unpackhi_epi32(m1, m3);+ tt = _mm_unpacklo_epi32(m2, t3);+ t3 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(0, 1, 3, 2));+ g2(&rows[0], &rows[1], &rows[2], &rows[3], t3);+ undiagonalize(&rows[0], &rows[2], &rows[3]);+ m0 = t0;+ m1 = t1;+ m2 = t2;+ m3 = t3;++ // Round 6+ t0 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(3, 1, 1, 2));+ t0 = _mm_shuffle_epi32(t0, _MM_SHUFFLE(0, 3, 2, 1));+ g1(&rows[0], &rows[1], &rows[2], &rows[3], t0);+ t1 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(3, 3, 2, 2));+ tt = _mm_shuffle_epi32(m0, _MM_SHUFFLE(0, 0, 3, 3));+ t1 = blend_epi16(tt, t1, 0xCC);+ g2(&rows[0], &rows[1], &rows[2], &rows[3], t1);+ diagonalize(&rows[0], &rows[2], &rows[3]);+ t2 = _mm_unpacklo_epi64(m3, m1);+ tt = blend_epi16(t2, m2, 0xC0);+ t2 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(1, 3, 2, 0));+ g1(&rows[0], &rows[1], &rows[2], &rows[3], t2);+ t3 = _mm_unpackhi_epi32(m1, m3);+ tt = _mm_unpacklo_epi32(m2, t3);+ t3 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(0, 1, 3, 2));+ g2(&rows[0], &rows[1], &rows[2], &rows[3], t3);+ undiagonalize(&rows[0], &rows[2], &rows[3]);+ m0 = t0;+ m1 = t1;+ m2 = t2;+ m3 = t3;++ // Round 7+ t0 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(3, 1, 1, 2));+ t0 = _mm_shuffle_epi32(t0, _MM_SHUFFLE(0, 3, 2, 1));+ g1(&rows[0], &rows[1], &rows[2], &rows[3], t0);+ t1 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(3, 3, 2, 2));+ tt = _mm_shuffle_epi32(m0, _MM_SHUFFLE(0, 0, 3, 3));+ t1 = blend_epi16(tt, t1, 0xCC);+ g2(&rows[0], &rows[1], &rows[2], &rows[3], t1);+ diagonalize(&rows[0], &rows[2], &rows[3]);+ t2 = _mm_unpacklo_epi64(m3, m1);+ tt = blend_epi16(t2, m2, 0xC0);+ t2 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(1, 3, 2, 0));+ g1(&rows[0], &rows[1], &rows[2], &rows[3], t2);+ t3 = _mm_unpackhi_epi32(m1, m3);+ tt = _mm_unpacklo_epi32(m2, t3);+ t3 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(0, 1, 3, 2));+ g2(&rows[0], &rows[1], &rows[2], &rows[3], t3);+ undiagonalize(&rows[0], &rows[2], &rows[3]);+}++void blake3_compress_in_place_sse2(uint32_t cv[8],+ const uint8_t block[BLAKE3_BLOCK_LEN],+ uint8_t block_len, uint64_t counter,+ uint8_t flags) {+ __m128i rows[4];+ compress_pre(rows, cv, block, block_len, counter, flags);+ storeu(xorv(rows[0], rows[2]), (uint8_t *)&cv[0]);+ storeu(xorv(rows[1], rows[3]), (uint8_t *)&cv[4]);+}++void blake3_compress_xof_sse2(const uint32_t cv[8],+ const uint8_t block[BLAKE3_BLOCK_LEN],+ uint8_t block_len, uint64_t counter,+ uint8_t flags, uint8_t out[64]) {+ __m128i rows[4];+ compress_pre(rows, cv, block, block_len, counter, flags);+ storeu(xorv(rows[0], rows[2]), &out[0]);+ storeu(xorv(rows[1], rows[3]), &out[16]);+ storeu(xorv(rows[2], loadu((uint8_t *)&cv[0])), &out[32]);+ storeu(xorv(rows[3], loadu((uint8_t *)&cv[4])), &out[48]);+}++INLINE void round_fn(__m128i v[16], __m128i m[16], size_t r) {+ v[0] = addv(v[0], m[(size_t)MSG_SCHEDULE[r][0]]);+ v[1] = addv(v[1], m[(size_t)MSG_SCHEDULE[r][2]]);+ v[2] = addv(v[2], m[(size_t)MSG_SCHEDULE[r][4]]);+ v[3] = addv(v[3], m[(size_t)MSG_SCHEDULE[r][6]]);+ v[0] = addv(v[0], v[4]);+ v[1] = addv(v[1], v[5]);+ v[2] = addv(v[2], v[6]);+ v[3] = addv(v[3], v[7]);+ v[12] = xorv(v[12], v[0]);+ v[13] = xorv(v[13], v[1]);+ v[14] = xorv(v[14], v[2]);+ v[15] = xorv(v[15], v[3]);+ v[12] = rot16(v[12]);+ v[13] = rot16(v[13]);+ v[14] = rot16(v[14]);+ v[15] = rot16(v[15]);+ v[8] = addv(v[8], v[12]);+ v[9] = addv(v[9], v[13]);+ v[10] = addv(v[10], v[14]);+ v[11] = addv(v[11], v[15]);+ v[4] = xorv(v[4], v[8]);+ v[5] = xorv(v[5], v[9]);+ v[6] = xorv(v[6], v[10]);+ v[7] = xorv(v[7], v[11]);+ v[4] = rot12(v[4]);+ v[5] = rot12(v[5]);+ v[6] = rot12(v[6]);+ v[7] = rot12(v[7]);+ v[0] = addv(v[0], m[(size_t)MSG_SCHEDULE[r][1]]);+ v[1] = addv(v[1], m[(size_t)MSG_SCHEDULE[r][3]]);+ v[2] = addv(v[2], m[(size_t)MSG_SCHEDULE[r][5]]);+ v[3] = addv(v[3], m[(size_t)MSG_SCHEDULE[r][7]]);+ v[0] = addv(v[0], v[4]);+ v[1] = addv(v[1], v[5]);+ v[2] = addv(v[2], v[6]);+ v[3] = addv(v[3], v[7]);+ v[12] = xorv(v[12], v[0]);+ v[13] = xorv(v[13], v[1]);+ v[14] = xorv(v[14], v[2]);+ v[15] = xorv(v[15], v[3]);+ v[12] = rot8(v[12]);+ v[13] = rot8(v[13]);+ v[14] = rot8(v[14]);+ v[15] = rot8(v[15]);+ v[8] = addv(v[8], v[12]);+ v[9] = addv(v[9], v[13]);+ v[10] = addv(v[10], v[14]);+ v[11] = addv(v[11], v[15]);+ v[4] = xorv(v[4], v[8]);+ v[5] = xorv(v[5], v[9]);+ v[6] = xorv(v[6], v[10]);+ v[7] = xorv(v[7], v[11]);+ v[4] = rot7(v[4]);+ v[5] = rot7(v[5]);+ v[6] = rot7(v[6]);+ v[7] = rot7(v[7]);++ v[0] = addv(v[0], m[(size_t)MSG_SCHEDULE[r][8]]);+ v[1] = addv(v[1], m[(size_t)MSG_SCHEDULE[r][10]]);+ v[2] = addv(v[2], m[(size_t)MSG_SCHEDULE[r][12]]);+ v[3] = addv(v[3], m[(size_t)MSG_SCHEDULE[r][14]]);+ v[0] = addv(v[0], v[5]);+ v[1] = addv(v[1], v[6]);+ v[2] = addv(v[2], v[7]);+ v[3] = addv(v[3], v[4]);+ v[15] = xorv(v[15], v[0]);+ v[12] = xorv(v[12], v[1]);+ v[13] = xorv(v[13], v[2]);+ v[14] = xorv(v[14], v[3]);+ v[15] = rot16(v[15]);+ v[12] = rot16(v[12]);+ v[13] = rot16(v[13]);+ v[14] = rot16(v[14]);+ v[10] = addv(v[10], v[15]);+ v[11] = addv(v[11], v[12]);+ v[8] = addv(v[8], v[13]);+ v[9] = addv(v[9], v[14]);+ v[5] = xorv(v[5], v[10]);+ v[6] = xorv(v[6], v[11]);+ v[7] = xorv(v[7], v[8]);+ v[4] = xorv(v[4], v[9]);+ v[5] = rot12(v[5]);+ v[6] = rot12(v[6]);+ v[7] = rot12(v[7]);+ v[4] = rot12(v[4]);+ v[0] = addv(v[0], m[(size_t)MSG_SCHEDULE[r][9]]);+ v[1] = addv(v[1], m[(size_t)MSG_SCHEDULE[r][11]]);+ v[2] = addv(v[2], m[(size_t)MSG_SCHEDULE[r][13]]);+ v[3] = addv(v[3], m[(size_t)MSG_SCHEDULE[r][15]]);+ v[0] = addv(v[0], v[5]);+ v[1] = addv(v[1], v[6]);+ v[2] = addv(v[2], v[7]);+ v[3] = addv(v[3], v[4]);+ v[15] = xorv(v[15], v[0]);+ v[12] = xorv(v[12], v[1]);+ v[13] = xorv(v[13], v[2]);+ v[14] = xorv(v[14], v[3]);+ v[15] = rot8(v[15]);+ v[12] = rot8(v[12]);+ v[13] = rot8(v[13]);+ v[14] = rot8(v[14]);+ v[10] = addv(v[10], v[15]);+ v[11] = addv(v[11], v[12]);+ v[8] = addv(v[8], v[13]);+ v[9] = addv(v[9], v[14]);+ v[5] = xorv(v[5], v[10]);+ v[6] = xorv(v[6], v[11]);+ v[7] = xorv(v[7], v[8]);+ v[4] = xorv(v[4], v[9]);+ v[5] = rot7(v[5]);+ v[6] = rot7(v[6]);+ v[7] = rot7(v[7]);+ v[4] = rot7(v[4]);+}++INLINE void transpose_vecs(__m128i vecs[DEGREE]) {+ // Interleave 32-bit lanes. The low unpack is lanes 00/11 and the high is+ // 22/33. Note that this doesn't split the vector into two lanes, as the+ // AVX2 counterparts do.+ __m128i ab_01 = _mm_unpacklo_epi32(vecs[0], vecs[1]);+ __m128i ab_23 = _mm_unpackhi_epi32(vecs[0], vecs[1]);+ __m128i cd_01 = _mm_unpacklo_epi32(vecs[2], vecs[3]);+ __m128i cd_23 = _mm_unpackhi_epi32(vecs[2], vecs[3]);++ // Interleave 64-bit lanes.+ __m128i abcd_0 = _mm_unpacklo_epi64(ab_01, cd_01);+ __m128i abcd_1 = _mm_unpackhi_epi64(ab_01, cd_01);+ __m128i abcd_2 = _mm_unpacklo_epi64(ab_23, cd_23);+ __m128i abcd_3 = _mm_unpackhi_epi64(ab_23, cd_23);++ vecs[0] = abcd_0;+ vecs[1] = abcd_1;+ vecs[2] = abcd_2;+ vecs[3] = abcd_3;+}++INLINE void transpose_msg_vecs(const uint8_t *const *inputs,+ size_t block_offset, __m128i out[16]) {+ out[0] = loadu(&inputs[0][block_offset + 0 * sizeof(__m128i)]);+ out[1] = loadu(&inputs[1][block_offset + 0 * sizeof(__m128i)]);+ out[2] = loadu(&inputs[2][block_offset + 0 * sizeof(__m128i)]);+ out[3] = loadu(&inputs[3][block_offset + 0 * sizeof(__m128i)]);+ out[4] = loadu(&inputs[0][block_offset + 1 * sizeof(__m128i)]);+ out[5] = loadu(&inputs[1][block_offset + 1 * sizeof(__m128i)]);+ out[6] = loadu(&inputs[2][block_offset + 1 * sizeof(__m128i)]);+ out[7] = loadu(&inputs[3][block_offset + 1 * sizeof(__m128i)]);+ out[8] = loadu(&inputs[0][block_offset + 2 * sizeof(__m128i)]);+ out[9] = loadu(&inputs[1][block_offset + 2 * sizeof(__m128i)]);+ out[10] = loadu(&inputs[2][block_offset + 2 * sizeof(__m128i)]);+ out[11] = loadu(&inputs[3][block_offset + 2 * sizeof(__m128i)]);+ out[12] = loadu(&inputs[0][block_offset + 3 * sizeof(__m128i)]);+ out[13] = loadu(&inputs[1][block_offset + 3 * sizeof(__m128i)]);+ out[14] = loadu(&inputs[2][block_offset + 3 * sizeof(__m128i)]);+ out[15] = loadu(&inputs[3][block_offset + 3 * sizeof(__m128i)]);+ for (size_t i = 0; i < 4; ++i) {+ _mm_prefetch((const void *)&inputs[i][block_offset + 256], _MM_HINT_T0);+ }+ transpose_vecs(&out[0]);+ transpose_vecs(&out[4]);+ transpose_vecs(&out[8]);+ transpose_vecs(&out[12]);+}++INLINE void load_counters(uint64_t counter, bool increment_counter,+ __m128i *out_lo, __m128i *out_hi) {+ const __m128i mask = _mm_set1_epi32(-(int32_t)increment_counter);+ const __m128i add0 = _mm_set_epi32(3, 2, 1, 0);+ const __m128i add1 = _mm_and_si128(mask, add0);+ __m128i l = _mm_add_epi32(_mm_set1_epi32((int32_t)counter), add1);+ __m128i carry = _mm_cmpgt_epi32(_mm_xor_si128(add1, _mm_set1_epi32(0x80000000)), + _mm_xor_si128( l, _mm_set1_epi32(0x80000000)));+ __m128i h = _mm_sub_epi32(_mm_set1_epi32((int32_t)(counter >> 32)), carry);+ *out_lo = l;+ *out_hi = h;+}++static+void blake3_hash4_sse2(const uint8_t *const *inputs, size_t blocks,+ const uint32_t key[8], uint64_t counter,+ bool increment_counter, uint8_t flags,+ uint8_t flags_start, uint8_t flags_end, uint8_t *out) {+ __m128i h_vecs[8] = {+ set1(key[0]), set1(key[1]), set1(key[2]), set1(key[3]),+ set1(key[4]), set1(key[5]), set1(key[6]), set1(key[7]),+ };+ __m128i counter_low_vec, counter_high_vec;+ load_counters(counter, increment_counter, &counter_low_vec,+ &counter_high_vec);+ uint8_t block_flags = flags | flags_start;++ for (size_t block = 0; block < blocks; block++) {+ if (block + 1 == blocks) {+ block_flags |= flags_end;+ }+ __m128i block_len_vec = set1(BLAKE3_BLOCK_LEN);+ __m128i block_flags_vec = set1(block_flags);+ __m128i msg_vecs[16];+ transpose_msg_vecs(inputs, block * BLAKE3_BLOCK_LEN, msg_vecs);++ __m128i v[16] = {+ h_vecs[0], h_vecs[1], h_vecs[2], h_vecs[3],+ h_vecs[4], h_vecs[5], h_vecs[6], h_vecs[7],+ set1(IV[0]), set1(IV[1]), set1(IV[2]), set1(IV[3]),+ counter_low_vec, counter_high_vec, block_len_vec, block_flags_vec,+ };+ round_fn(v, msg_vecs, 0);+ round_fn(v, msg_vecs, 1);+ round_fn(v, msg_vecs, 2);+ round_fn(v, msg_vecs, 3);+ round_fn(v, msg_vecs, 4);+ round_fn(v, msg_vecs, 5);+ round_fn(v, msg_vecs, 6);+ h_vecs[0] = xorv(v[0], v[8]);+ h_vecs[1] = xorv(v[1], v[9]);+ h_vecs[2] = xorv(v[2], v[10]);+ h_vecs[3] = xorv(v[3], v[11]);+ h_vecs[4] = xorv(v[4], v[12]);+ h_vecs[5] = xorv(v[5], v[13]);+ h_vecs[6] = xorv(v[6], v[14]);+ h_vecs[7] = xorv(v[7], v[15]);++ block_flags = flags;+ }++ transpose_vecs(&h_vecs[0]);+ transpose_vecs(&h_vecs[4]);+ // The first four vecs now contain the first half of each output, and the+ // second four vecs contain the second half of each output.+ storeu(h_vecs[0], &out[0 * sizeof(__m128i)]);+ storeu(h_vecs[4], &out[1 * sizeof(__m128i)]);+ storeu(h_vecs[1], &out[2 * sizeof(__m128i)]);+ storeu(h_vecs[5], &out[3 * sizeof(__m128i)]);+ storeu(h_vecs[2], &out[4 * sizeof(__m128i)]);+ storeu(h_vecs[6], &out[5 * sizeof(__m128i)]);+ storeu(h_vecs[3], &out[6 * sizeof(__m128i)]);+ storeu(h_vecs[7], &out[7 * sizeof(__m128i)]);+}++INLINE void hash_one_sse2(const uint8_t *input, size_t blocks,+ const uint32_t key[8], uint64_t counter,+ uint8_t flags, uint8_t flags_start,+ uint8_t flags_end, uint8_t out[BLAKE3_OUT_LEN]) {+ uint32_t cv[8];+ memcpy(cv, key, BLAKE3_KEY_LEN);+ uint8_t block_flags = flags | flags_start;+ while (blocks > 0) {+ if (blocks == 1) {+ block_flags |= flags_end;+ }+ blake3_compress_in_place_sse2(cv, input, BLAKE3_BLOCK_LEN, counter,+ block_flags);+ input = &input[BLAKE3_BLOCK_LEN];+ blocks -= 1;+ block_flags = flags;+ }+ memcpy(out, cv, BLAKE3_OUT_LEN);+}++void blake3_hash_many_sse2(const uint8_t *const *inputs, size_t num_inputs,+ size_t blocks, const uint32_t key[8],+ uint64_t counter, bool increment_counter,+ uint8_t flags, uint8_t flags_start,+ uint8_t flags_end, uint8_t *out) {+ while (num_inputs >= DEGREE) {+ blake3_hash4_sse2(inputs, blocks, key, counter, increment_counter, flags,+ flags_start, flags_end, out);+ if (increment_counter) {+ counter += DEGREE;+ }+ inputs += DEGREE;+ num_inputs -= DEGREE;+ out = &out[DEGREE * BLAKE3_OUT_LEN];+ }+ while (num_inputs > 0) {+ hash_one_sse2(inputs[0], blocks, key, counter, flags, flags_start,+ flags_end, out);+ if (increment_counter) {+ counter += 1;+ }+ inputs += 1;+ num_inputs -= 1;+ out = &out[BLAKE3_OUT_LEN];+ }+}--- /dev/null+++ b/veins/src/crypto/blake3/blake3_sse41.c@@ -0,0 +1,560 @@+#include "blake3_impl.h"++#include <immintrin.h>++#define DEGREE 4++#define _mm_shuffle_ps2(a, b, c) \+ (_mm_castps_si128( \+ _mm_shuffle_ps(_mm_castsi128_ps(a), _mm_castsi128_ps(b), (c))))++INLINE __m128i loadu(const uint8_t src[16]) {+ return _mm_loadu_si128((const __m128i *)src);+}++INLINE void storeu(__m128i src, uint8_t dest[16]) {+ _mm_storeu_si128((__m128i *)dest, src);+}++INLINE __m128i addv(__m128i a, __m128i b) { return _mm_add_epi32(a, b); }++// Note that clang-format doesn't like the name "xor" for some reason.+INLINE __m128i xorv(__m128i a, __m128i b) { return _mm_xor_si128(a, b); }++INLINE __m128i set1(uint32_t x) { return _mm_set1_epi32((int32_t)x); }++INLINE __m128i set4(uint32_t a, uint32_t b, uint32_t c, uint32_t d) {+ return _mm_setr_epi32((int32_t)a, (int32_t)b, (int32_t)c, (int32_t)d);+}++INLINE __m128i rot16(__m128i x) {+ return _mm_shuffle_epi8(+ x, _mm_set_epi8(13, 12, 15, 14, 9, 8, 11, 10, 5, 4, 7, 6, 1, 0, 3, 2));+}++INLINE __m128i rot12(__m128i x) {+ return xorv(_mm_srli_epi32(x, 12), _mm_slli_epi32(x, 32 - 12));+}++INLINE __m128i rot8(__m128i x) {+ return _mm_shuffle_epi8(+ x, _mm_set_epi8(12, 15, 14, 13, 8, 11, 10, 9, 4, 7, 6, 5, 0, 3, 2, 1));+}++INLINE __m128i rot7(__m128i x) {+ return xorv(_mm_srli_epi32(x, 7), _mm_slli_epi32(x, 32 - 7));+}++INLINE void g1(__m128i *row0, __m128i *row1, __m128i *row2, __m128i *row3,+ __m128i m) {+ *row0 = addv(addv(*row0, m), *row1);+ *row3 = xorv(*row3, *row0);+ *row3 = rot16(*row3);+ *row2 = addv(*row2, *row3);+ *row1 = xorv(*row1, *row2);+ *row1 = rot12(*row1);+}++INLINE void g2(__m128i *row0, __m128i *row1, __m128i *row2, __m128i *row3,+ __m128i m) {+ *row0 = addv(addv(*row0, m), *row1);+ *row3 = xorv(*row3, *row0);+ *row3 = rot8(*row3);+ *row2 = addv(*row2, *row3);+ *row1 = xorv(*row1, *row2);+ *row1 = rot7(*row1);+}++// Note the optimization here of leaving row1 as the unrotated row, rather than+// row0. All the message loads below are adjusted to compensate for this. See+// discussion at https://github.com/sneves/blake2-avx2/pull/4+INLINE void diagonalize(__m128i *row0, __m128i *row2, __m128i *row3) {+ *row0 = _mm_shuffle_epi32(*row0, _MM_SHUFFLE(2, 1, 0, 3));+ *row3 = _mm_shuffle_epi32(*row3, _MM_SHUFFLE(1, 0, 3, 2));+ *row2 = _mm_shuffle_epi32(*row2, _MM_SHUFFLE(0, 3, 2, 1));+}++INLINE void undiagonalize(__m128i *row0, __m128i *row2, __m128i *row3) {+ *row0 = _mm_shuffle_epi32(*row0, _MM_SHUFFLE(0, 3, 2, 1));+ *row3 = _mm_shuffle_epi32(*row3, _MM_SHUFFLE(1, 0, 3, 2));+ *row2 = _mm_shuffle_epi32(*row2, _MM_SHUFFLE(2, 1, 0, 3));+}++INLINE void compress_pre(__m128i rows[4], const uint32_t cv[8],+ const uint8_t block[BLAKE3_BLOCK_LEN],+ uint8_t block_len, uint64_t counter, uint8_t flags) {+ rows[0] = loadu((uint8_t *)&cv[0]);+ rows[1] = loadu((uint8_t *)&cv[4]);+ rows[2] = set4(IV[0], IV[1], IV[2], IV[3]);+ rows[3] = set4(counter_low(counter), counter_high(counter),+ (uint32_t)block_len, (uint32_t)flags);++ __m128i m0 = loadu(&block[sizeof(__m128i) * 0]);+ __m128i m1 = loadu(&block[sizeof(__m128i) * 1]);+ __m128i m2 = loadu(&block[sizeof(__m128i) * 2]);+ __m128i m3 = loadu(&block[sizeof(__m128i) * 3]);++ __m128i t0, t1, t2, t3, tt;++ // Round 1. The first round permutes the message words from the original+ // input order, into the groups that get mixed in parallel.+ t0 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(2, 0, 2, 0)); // 6 4 2 0+ g1(&rows[0], &rows[1], &rows[2], &rows[3], t0);+ t1 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(3, 1, 3, 1)); // 7 5 3 1+ g2(&rows[0], &rows[1], &rows[2], &rows[3], t1);+ diagonalize(&rows[0], &rows[2], &rows[3]);+ t2 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(2, 0, 2, 0)); // 14 12 10 8+ t2 = _mm_shuffle_epi32(t2, _MM_SHUFFLE(2, 1, 0, 3)); // 12 10 8 14+ g1(&rows[0], &rows[1], &rows[2], &rows[3], t2);+ t3 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(3, 1, 3, 1)); // 15 13 11 9+ t3 = _mm_shuffle_epi32(t3, _MM_SHUFFLE(2, 1, 0, 3)); // 13 11 9 15+ g2(&rows[0], &rows[1], &rows[2], &rows[3], t3);+ undiagonalize(&rows[0], &rows[2], &rows[3]);+ m0 = t0;+ m1 = t1;+ m2 = t2;+ m3 = t3;++ // Round 2. This round and all following rounds apply a fixed permutation+ // to the message words from the round before.+ t0 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(3, 1, 1, 2));+ t0 = _mm_shuffle_epi32(t0, _MM_SHUFFLE(0, 3, 2, 1));+ g1(&rows[0], &rows[1], &rows[2], &rows[3], t0);+ t1 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(3, 3, 2, 2));+ tt = _mm_shuffle_epi32(m0, _MM_SHUFFLE(0, 0, 3, 3));+ t1 = _mm_blend_epi16(tt, t1, 0xCC);+ g2(&rows[0], &rows[1], &rows[2], &rows[3], t1);+ diagonalize(&rows[0], &rows[2], &rows[3]);+ t2 = _mm_unpacklo_epi64(m3, m1);+ tt = _mm_blend_epi16(t2, m2, 0xC0);+ t2 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(1, 3, 2, 0));+ g1(&rows[0], &rows[1], &rows[2], &rows[3], t2);+ t3 = _mm_unpackhi_epi32(m1, m3);+ tt = _mm_unpacklo_epi32(m2, t3);+ t3 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(0, 1, 3, 2));+ g2(&rows[0], &rows[1], &rows[2], &rows[3], t3);+ undiagonalize(&rows[0], &rows[2], &rows[3]);+ m0 = t0;+ m1 = t1;+ m2 = t2;+ m3 = t3;++ // Round 3+ t0 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(3, 1, 1, 2));+ t0 = _mm_shuffle_epi32(t0, _MM_SHUFFLE(0, 3, 2, 1));+ g1(&rows[0], &rows[1], &rows[2], &rows[3], t0);+ t1 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(3, 3, 2, 2));+ tt = _mm_shuffle_epi32(m0, _MM_SHUFFLE(0, 0, 3, 3));+ t1 = _mm_blend_epi16(tt, t1, 0xCC);+ g2(&rows[0], &rows[1], &rows[2], &rows[3], t1);+ diagonalize(&rows[0], &rows[2], &rows[3]);+ t2 = _mm_unpacklo_epi64(m3, m1);+ tt = _mm_blend_epi16(t2, m2, 0xC0);+ t2 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(1, 3, 2, 0));+ g1(&rows[0], &rows[1], &rows[2], &rows[3], t2);+ t3 = _mm_unpackhi_epi32(m1, m3);+ tt = _mm_unpacklo_epi32(m2, t3);+ t3 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(0, 1, 3, 2));+ g2(&rows[0], &rows[1], &rows[2], &rows[3], t3);+ undiagonalize(&rows[0], &rows[2], &rows[3]);+ m0 = t0;+ m1 = t1;+ m2 = t2;+ m3 = t3;++ // Round 4+ t0 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(3, 1, 1, 2));+ t0 = _mm_shuffle_epi32(t0, _MM_SHUFFLE(0, 3, 2, 1));+ g1(&rows[0], &rows[1], &rows[2], &rows[3], t0);+ t1 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(3, 3, 2, 2));+ tt = _mm_shuffle_epi32(m0, _MM_SHUFFLE(0, 0, 3, 3));+ t1 = _mm_blend_epi16(tt, t1, 0xCC);+ g2(&rows[0], &rows[1], &rows[2], &rows[3], t1);+ diagonalize(&rows[0], &rows[2], &rows[3]);+ t2 = _mm_unpacklo_epi64(m3, m1);+ tt = _mm_blend_epi16(t2, m2, 0xC0);+ t2 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(1, 3, 2, 0));+ g1(&rows[0], &rows[1], &rows[2], &rows[3], t2);+ t3 = _mm_unpackhi_epi32(m1, m3);+ tt = _mm_unpacklo_epi32(m2, t3);+ t3 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(0, 1, 3, 2));+ g2(&rows[0], &rows[1], &rows[2], &rows[3], t3);+ undiagonalize(&rows[0], &rows[2], &rows[3]);+ m0 = t0;+ m1 = t1;+ m2 = t2;+ m3 = t3;++ // Round 5+ t0 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(3, 1, 1, 2));+ t0 = _mm_shuffle_epi32(t0, _MM_SHUFFLE(0, 3, 2, 1));+ g1(&rows[0], &rows[1], &rows[2], &rows[3], t0);+ t1 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(3, 3, 2, 2));+ tt = _mm_shuffle_epi32(m0, _MM_SHUFFLE(0, 0, 3, 3));+ t1 = _mm_blend_epi16(tt, t1, 0xCC);+ g2(&rows[0], &rows[1], &rows[2], &rows[3], t1);+ diagonalize(&rows[0], &rows[2], &rows[3]);+ t2 = _mm_unpacklo_epi64(m3, m1);+ tt = _mm_blend_epi16(t2, m2, 0xC0);+ t2 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(1, 3, 2, 0));+ g1(&rows[0], &rows[1], &rows[2], &rows[3], t2);+ t3 = _mm_unpackhi_epi32(m1, m3);+ tt = _mm_unpacklo_epi32(m2, t3);+ t3 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(0, 1, 3, 2));+ g2(&rows[0], &rows[1], &rows[2], &rows[3], t3);+ undiagonalize(&rows[0], &rows[2], &rows[3]);+ m0 = t0;+ m1 = t1;+ m2 = t2;+ m3 = t3;++ // Round 6+ t0 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(3, 1, 1, 2));+ t0 = _mm_shuffle_epi32(t0, _MM_SHUFFLE(0, 3, 2, 1));+ g1(&rows[0], &rows[1], &rows[2], &rows[3], t0);+ t1 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(3, 3, 2, 2));+ tt = _mm_shuffle_epi32(m0, _MM_SHUFFLE(0, 0, 3, 3));+ t1 = _mm_blend_epi16(tt, t1, 0xCC);+ g2(&rows[0], &rows[1], &rows[2], &rows[3], t1);+ diagonalize(&rows[0], &rows[2], &rows[3]);+ t2 = _mm_unpacklo_epi64(m3, m1);+ tt = _mm_blend_epi16(t2, m2, 0xC0);+ t2 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(1, 3, 2, 0));+ g1(&rows[0], &rows[1], &rows[2], &rows[3], t2);+ t3 = _mm_unpackhi_epi32(m1, m3);+ tt = _mm_unpacklo_epi32(m2, t3);+ t3 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(0, 1, 3, 2));+ g2(&rows[0], &rows[1], &rows[2], &rows[3], t3);+ undiagonalize(&rows[0], &rows[2], &rows[3]);+ m0 = t0;+ m1 = t1;+ m2 = t2;+ m3 = t3;++ // Round 7+ t0 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(3, 1, 1, 2));+ t0 = _mm_shuffle_epi32(t0, _MM_SHUFFLE(0, 3, 2, 1));+ g1(&rows[0], &rows[1], &rows[2], &rows[3], t0);+ t1 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(3, 3, 2, 2));+ tt = _mm_shuffle_epi32(m0, _MM_SHUFFLE(0, 0, 3, 3));+ t1 = _mm_blend_epi16(tt, t1, 0xCC);+ g2(&rows[0], &rows[1], &rows[2], &rows[3], t1);+ diagonalize(&rows[0], &rows[2], &rows[3]);+ t2 = _mm_unpacklo_epi64(m3, m1);+ tt = _mm_blend_epi16(t2, m2, 0xC0);+ t2 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(1, 3, 2, 0));+ g1(&rows[0], &rows[1], &rows[2], &rows[3], t2);+ t3 = _mm_unpackhi_epi32(m1, m3);+ tt = _mm_unpacklo_epi32(m2, t3);+ t3 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(0, 1, 3, 2));+ g2(&rows[0], &rows[1], &rows[2], &rows[3], t3);+ undiagonalize(&rows[0], &rows[2], &rows[3]);+}++void blake3_compress_in_place_sse41(uint32_t cv[8],+ const uint8_t block[BLAKE3_BLOCK_LEN],+ uint8_t block_len, uint64_t counter,+ uint8_t flags) {+ __m128i rows[4];+ compress_pre(rows, cv, block, block_len, counter, flags);+ storeu(xorv(rows[0], rows[2]), (uint8_t *)&cv[0]);+ storeu(xorv(rows[1], rows[3]), (uint8_t *)&cv[4]);+}++void blake3_compress_xof_sse41(const uint32_t cv[8],+ const uint8_t block[BLAKE3_BLOCK_LEN],+ uint8_t block_len, uint64_t counter,+ uint8_t flags, uint8_t out[64]) {+ __m128i rows[4];+ compress_pre(rows, cv, block, block_len, counter, flags);+ storeu(xorv(rows[0], rows[2]), &out[0]);+ storeu(xorv(rows[1], rows[3]), &out[16]);+ storeu(xorv(rows[2], loadu((uint8_t *)&cv[0])), &out[32]);+ storeu(xorv(rows[3], loadu((uint8_t *)&cv[4])), &out[48]);+}++INLINE void round_fn(__m128i v[16], __m128i m[16], size_t r) {+ v[0] = addv(v[0], m[(size_t)MSG_SCHEDULE[r][0]]);+ v[1] = addv(v[1], m[(size_t)MSG_SCHEDULE[r][2]]);+ v[2] = addv(v[2], m[(size_t)MSG_SCHEDULE[r][4]]);+ v[3] = addv(v[3], m[(size_t)MSG_SCHEDULE[r][6]]);+ v[0] = addv(v[0], v[4]);+ v[1] = addv(v[1], v[5]);+ v[2] = addv(v[2], v[6]);+ v[3] = addv(v[3], v[7]);+ v[12] = xorv(v[12], v[0]);+ v[13] = xorv(v[13], v[1]);+ v[14] = xorv(v[14], v[2]);+ v[15] = xorv(v[15], v[3]);+ v[12] = rot16(v[12]);+ v[13] = rot16(v[13]);+ v[14] = rot16(v[14]);+ v[15] = rot16(v[15]);+ v[8] = addv(v[8], v[12]);+ v[9] = addv(v[9], v[13]);+ v[10] = addv(v[10], v[14]);+ v[11] = addv(v[11], v[15]);+ v[4] = xorv(v[4], v[8]);+ v[5] = xorv(v[5], v[9]);+ v[6] = xorv(v[6], v[10]);+ v[7] = xorv(v[7], v[11]);+ v[4] = rot12(v[4]);+ v[5] = rot12(v[5]);+ v[6] = rot12(v[6]);+ v[7] = rot12(v[7]);+ v[0] = addv(v[0], m[(size_t)MSG_SCHEDULE[r][1]]);+ v[1] = addv(v[1], m[(size_t)MSG_SCHEDULE[r][3]]);+ v[2] = addv(v[2], m[(size_t)MSG_SCHEDULE[r][5]]);+ v[3] = addv(v[3], m[(size_t)MSG_SCHEDULE[r][7]]);+ v[0] = addv(v[0], v[4]);+ v[1] = addv(v[1], v[5]);+ v[2] = addv(v[2], v[6]);+ v[3] = addv(v[3], v[7]);+ v[12] = xorv(v[12], v[0]);+ v[13] = xorv(v[13], v[1]);+ v[14] = xorv(v[14], v[2]);+ v[15] = xorv(v[15], v[3]);+ v[12] = rot8(v[12]);+ v[13] = rot8(v[13]);+ v[14] = rot8(v[14]);+ v[15] = rot8(v[15]);+ v[8] = addv(v[8], v[12]);+ v[9] = addv(v[9], v[13]);+ v[10] = addv(v[10], v[14]);+ v[11] = addv(v[11], v[15]);+ v[4] = xorv(v[4], v[8]);+ v[5] = xorv(v[5], v[9]);+ v[6] = xorv(v[6], v[10]);+ v[7] = xorv(v[7], v[11]);+ v[4] = rot7(v[4]);+ v[5] = rot7(v[5]);+ v[6] = rot7(v[6]);+ v[7] = rot7(v[7]);++ v[0] = addv(v[0], m[(size_t)MSG_SCHEDULE[r][8]]);+ v[1] = addv(v[1], m[(size_t)MSG_SCHEDULE[r][10]]);+ v[2] = addv(v[2], m[(size_t)MSG_SCHEDULE[r][12]]);+ v[3] = addv(v[3], m[(size_t)MSG_SCHEDULE[r][14]]);+ v[0] = addv(v[0], v[5]);+ v[1] = addv(v[1], v[6]);+ v[2] = addv(v[2], v[7]);+ v[3] = addv(v[3], v[4]);+ v[15] = xorv(v[15], v[0]);+ v[12] = xorv(v[12], v[1]);+ v[13] = xorv(v[13], v[2]);+ v[14] = xorv(v[14], v[3]);+ v[15] = rot16(v[15]);+ v[12] = rot16(v[12]);+ v[13] = rot16(v[13]);+ v[14] = rot16(v[14]);+ v[10] = addv(v[10], v[15]);+ v[11] = addv(v[11], v[12]);+ v[8] = addv(v[8], v[13]);+ v[9] = addv(v[9], v[14]);+ v[5] = xorv(v[5], v[10]);+ v[6] = xorv(v[6], v[11]);+ v[7] = xorv(v[7], v[8]);+ v[4] = xorv(v[4], v[9]);+ v[5] = rot12(v[5]);+ v[6] = rot12(v[6]);+ v[7] = rot12(v[7]);+ v[4] = rot12(v[4]);+ v[0] = addv(v[0], m[(size_t)MSG_SCHEDULE[r][9]]);+ v[1] = addv(v[1], m[(size_t)MSG_SCHEDULE[r][11]]);+ v[2] = addv(v[2], m[(size_t)MSG_SCHEDULE[r][13]]);+ v[3] = addv(v[3], m[(size_t)MSG_SCHEDULE[r][15]]);+ v[0] = addv(v[0], v[5]);+ v[1] = addv(v[1], v[6]);+ v[2] = addv(v[2], v[7]);+ v[3] = addv(v[3], v[4]);+ v[15] = xorv(v[15], v[0]);+ v[12] = xorv(v[12], v[1]);+ v[13] = xorv(v[13], v[2]);+ v[14] = xorv(v[14], v[3]);+ v[15] = rot8(v[15]);+ v[12] = rot8(v[12]);+ v[13] = rot8(v[13]);+ v[14] = rot8(v[14]);+ v[10] = addv(v[10], v[15]);+ v[11] = addv(v[11], v[12]);+ v[8] = addv(v[8], v[13]);+ v[9] = addv(v[9], v[14]);+ v[5] = xorv(v[5], v[10]);+ v[6] = xorv(v[6], v[11]);+ v[7] = xorv(v[7], v[8]);+ v[4] = xorv(v[4], v[9]);+ v[5] = rot7(v[5]);+ v[6] = rot7(v[6]);+ v[7] = rot7(v[7]);+ v[4] = rot7(v[4]);+}++INLINE void transpose_vecs(__m128i vecs[DEGREE]) {+ // Interleave 32-bit lanes. The low unpack is lanes 00/11 and the high is+ // 22/33. Note that this doesn't split the vector into two lanes, as the+ // AVX2 counterparts do.+ __m128i ab_01 = _mm_unpacklo_epi32(vecs[0], vecs[1]);+ __m128i ab_23 = _mm_unpackhi_epi32(vecs[0], vecs[1]);+ __m128i cd_01 = _mm_unpacklo_epi32(vecs[2], vecs[3]);+ __m128i cd_23 = _mm_unpackhi_epi32(vecs[2], vecs[3]);++ // Interleave 64-bit lanes.+ __m128i abcd_0 = _mm_unpacklo_epi64(ab_01, cd_01);+ __m128i abcd_1 = _mm_unpackhi_epi64(ab_01, cd_01);+ __m128i abcd_2 = _mm_unpacklo_epi64(ab_23, cd_23);+ __m128i abcd_3 = _mm_unpackhi_epi64(ab_23, cd_23);++ vecs[0] = abcd_0;+ vecs[1] = abcd_1;+ vecs[2] = abcd_2;+ vecs[3] = abcd_3;+}++INLINE void transpose_msg_vecs(const uint8_t *const *inputs,+ size_t block_offset, __m128i out[16]) {+ out[0] = loadu(&inputs[0][block_offset + 0 * sizeof(__m128i)]);+ out[1] = loadu(&inputs[1][block_offset + 0 * sizeof(__m128i)]);+ out[2] = loadu(&inputs[2][block_offset + 0 * sizeof(__m128i)]);+ out[3] = loadu(&inputs[3][block_offset + 0 * sizeof(__m128i)]);+ out[4] = loadu(&inputs[0][block_offset + 1 * sizeof(__m128i)]);+ out[5] = loadu(&inputs[1][block_offset + 1 * sizeof(__m128i)]);+ out[6] = loadu(&inputs[2][block_offset + 1 * sizeof(__m128i)]);+ out[7] = loadu(&inputs[3][block_offset + 1 * sizeof(__m128i)]);+ out[8] = loadu(&inputs[0][block_offset + 2 * sizeof(__m128i)]);+ out[9] = loadu(&inputs[1][block_offset + 2 * sizeof(__m128i)]);+ out[10] = loadu(&inputs[2][block_offset + 2 * sizeof(__m128i)]);+ out[11] = loadu(&inputs[3][block_offset + 2 * sizeof(__m128i)]);+ out[12] = loadu(&inputs[0][block_offset + 3 * sizeof(__m128i)]);+ out[13] = loadu(&inputs[1][block_offset + 3 * sizeof(__m128i)]);+ out[14] = loadu(&inputs[2][block_offset + 3 * sizeof(__m128i)]);+ out[15] = loadu(&inputs[3][block_offset + 3 * sizeof(__m128i)]);+ for (size_t i = 0; i < 4; ++i) {+ _mm_prefetch((const void *)&inputs[i][block_offset + 256], _MM_HINT_T0);+ }+ transpose_vecs(&out[0]);+ transpose_vecs(&out[4]);+ transpose_vecs(&out[8]);+ transpose_vecs(&out[12]);+}++INLINE void load_counters(uint64_t counter, bool increment_counter,+ __m128i *out_lo, __m128i *out_hi) {+ const __m128i mask = _mm_set1_epi32(-(int32_t)increment_counter);+ const __m128i add0 = _mm_set_epi32(3, 2, 1, 0);+ const __m128i add1 = _mm_and_si128(mask, add0);+ __m128i l = _mm_add_epi32(_mm_set1_epi32((int32_t)counter), add1);+ __m128i carry = _mm_cmpgt_epi32(_mm_xor_si128(add1, _mm_set1_epi32(0x80000000)), + _mm_xor_si128( l, _mm_set1_epi32(0x80000000)));+ __m128i h = _mm_sub_epi32(_mm_set1_epi32((int32_t)(counter >> 32)), carry);+ *out_lo = l;+ *out_hi = h;+}++static+void blake3_hash4_sse41(const uint8_t *const *inputs, size_t blocks,+ const uint32_t key[8], uint64_t counter,+ bool increment_counter, uint8_t flags,+ uint8_t flags_start, uint8_t flags_end, uint8_t *out) {+ __m128i h_vecs[8] = {+ set1(key[0]), set1(key[1]), set1(key[2]), set1(key[3]),+ set1(key[4]), set1(key[5]), set1(key[6]), set1(key[7]),+ };+ __m128i counter_low_vec, counter_high_vec;+ load_counters(counter, increment_counter, &counter_low_vec,+ &counter_high_vec);+ uint8_t block_flags = flags | flags_start;++ for (size_t block = 0; block < blocks; block++) {+ if (block + 1 == blocks) {+ block_flags |= flags_end;+ }+ __m128i block_len_vec = set1(BLAKE3_BLOCK_LEN);+ __m128i block_flags_vec = set1(block_flags);+ __m128i msg_vecs[16];+ transpose_msg_vecs(inputs, block * BLAKE3_BLOCK_LEN, msg_vecs);++ __m128i v[16] = {+ h_vecs[0], h_vecs[1], h_vecs[2], h_vecs[3],+ h_vecs[4], h_vecs[5], h_vecs[6], h_vecs[7],+ set1(IV[0]), set1(IV[1]), set1(IV[2]), set1(IV[3]),+ counter_low_vec, counter_high_vec, block_len_vec, block_flags_vec,+ };+ round_fn(v, msg_vecs, 0);+ round_fn(v, msg_vecs, 1);+ round_fn(v, msg_vecs, 2);+ round_fn(v, msg_vecs, 3);+ round_fn(v, msg_vecs, 4);+ round_fn(v, msg_vecs, 5);+ round_fn(v, msg_vecs, 6);+ h_vecs[0] = xorv(v[0], v[8]);+ h_vecs[1] = xorv(v[1], v[9]);+ h_vecs[2] = xorv(v[2], v[10]);+ h_vecs[3] = xorv(v[3], v[11]);+ h_vecs[4] = xorv(v[4], v[12]);+ h_vecs[5] = xorv(v[5], v[13]);+ h_vecs[6] = xorv(v[6], v[14]);+ h_vecs[7] = xorv(v[7], v[15]);++ block_flags = flags;+ }++ transpose_vecs(&h_vecs[0]);+ transpose_vecs(&h_vecs[4]);+ // The first four vecs now contain the first half of each output, and the+ // second four vecs contain the second half of each output.+ storeu(h_vecs[0], &out[0 * sizeof(__m128i)]);+ storeu(h_vecs[4], &out[1 * sizeof(__m128i)]);+ storeu(h_vecs[1], &out[2 * sizeof(__m128i)]);+ storeu(h_vecs[5], &out[3 * sizeof(__m128i)]);+ storeu(h_vecs[2], &out[4 * sizeof(__m128i)]);+ storeu(h_vecs[6], &out[5 * sizeof(__m128i)]);+ storeu(h_vecs[3], &out[6 * sizeof(__m128i)]);+ storeu(h_vecs[7], &out[7 * sizeof(__m128i)]);+}++INLINE void hash_one_sse41(const uint8_t *input, size_t blocks,+ const uint32_t key[8], uint64_t counter,+ uint8_t flags, uint8_t flags_start,+ uint8_t flags_end, uint8_t out[BLAKE3_OUT_LEN]) {+ uint32_t cv[8];+ memcpy(cv, key, BLAKE3_KEY_LEN);+ uint8_t block_flags = flags | flags_start;+ while (blocks > 0) {+ if (blocks == 1) {+ block_flags |= flags_end;+ }+ blake3_compress_in_place_sse41(cv, input, BLAKE3_BLOCK_LEN, counter,+ block_flags);+ input = &input[BLAKE3_BLOCK_LEN];+ blocks -= 1;+ block_flags = flags;+ }+ memcpy(out, cv, BLAKE3_OUT_LEN);+}++void blake3_hash_many_sse41(const uint8_t *const *inputs, size_t num_inputs,+ size_t blocks, const uint32_t key[8],+ uint64_t counter, bool increment_counter,+ uint8_t flags, uint8_t flags_start,+ uint8_t flags_end, uint8_t *out) {+ while (num_inputs >= DEGREE) {+ blake3_hash4_sse41(inputs, blocks, key, counter, increment_counter, flags,+ flags_start, flags_end, out);+ if (increment_counter) {+ counter += DEGREE;+ }+ inputs += DEGREE;+ num_inputs -= DEGREE;+ out = &out[DEGREE * BLAKE3_OUT_LEN];+ }+ while (num_inputs > 0) {+ hash_one_sse41(inputs[0], blocks, key, counter, flags, flags_start,+ flags_end, out);+ if (increment_counter) {+ counter += 1;+ }+ inputs += 1;+ num_inputs -= 1;+ out = &out[BLAKE3_OUT_LEN];+ }+}--- /dev/null+++ b/veins/src/crypto/blake3_c.c@@ -0,0 +1,29 @@+/* Thin adapter from the veins runtime to the vendored BLAKE3 C library. */++#include "blake3/blake3.h"++#include <stddef.h>+#include <stdint.h>++void veins_blake3(const uint8_t *data, size_t len, uint8_t out[32]) {+ blake3_hasher hasher;+ blake3_hasher_init(&hasher);+ blake3_hasher_update(&hasher, data, len);+ blake3_hasher_finalize(&hasher, out, 32);+}++size_t veins_blake3_state_size(void) {+ return sizeof(blake3_hasher);+}++void veins_blake3_init(void *state) {+ blake3_hasher_init((blake3_hasher *)state);+}++void veins_blake3_update(void *state, const uint8_t *data, size_t len) {+ blake3_hasher_update((blake3_hasher *)state, data, len);+}++void veins_blake3_final(void *state, uint8_t out[32]) {+ blake3_hasher_finalize((const blake3_hasher *)state, out, 32);+}--- /dev/null+++ b/veins/src/git/export.sx@@ -0,0 +1,1082 @@+/// Export veins commits into the bare git mirror.+///+/// Objects are written as loose git objects so export is incremental: only+/// commits missing from the ID map are visited, and each object is hashed+/// exactly once.++lib "z"++val str = use("std/string")+val stdio = use("std/stdio")+val msg = use("../core/msg.sx")+val bytes = use("../core/bytes.sx")+val buf = use("../core/buf.sx")+val lists = use("../core/lists.sx")+val prim = use("../core/primitives.sx")+val objid = use("../object/id.sx")+val tree = use("../object/tree.sx")+val commit = use("../object/commit.sx")+val view = use("../object/view.sx")+val graph = use("../object/graph.sx")+val treewalk = use("../object/treewalk.sx")+val content = use("../object/content.sx")+val store = use("../store/store.sx")+val state = use("../store/state.sx")+val layout = use("../store/layout.sx")+val files = use("../io/files.sx")+val nativeio = use("../io/native.sx")+val object = use("object.sx")+val format = use("format.sx")+val oidmap = use("oidmap.sx")+val gitmap = use("map.sx")+val lazy = use("lazy.sx")++extern (C) fn compress2(+ dest: ref u8,+ dest_len: ref u64,+ source: ref u8,+ source_len: u64,+ level: i32+) i32 = "compress2"+extern (C) fn compressBound(source_len: u64) u64 = "compressBound"++type ExportCtx = {+ repo: mut layout.Repo+ handles: list[ref store.Handle]+ commits: mut oidmap.OidMap+ trees: mut oidmap.OidMap+ blobs: mut oidmap.OidMap+ native: mut list[objid.Id]+ git: mut object.GitRepo+ git_open: mut bool+ failed: mut bool+}++type Mark = {+ id: mut objid.Id+ expanded: mut bool+}++fn copy_id(id: objid.Id) objid.Id = trust {+ val out: ref u8 = @alloc(32) as ref u8+ @memcpy(out as ref void, id.ptr as ref void, 32)+ return objid.id(out)+}++fn contains(ids: list[objid.Id], id: objid.Id) bool = trust {+ for x in ids {+ if objid.Id.eql(x, id) {+ return true+ }+ }+ return false+}++fn free_ids(ids: list[objid.Id]) void = trust {+ for id in ids {+ if id.ptr != none {+ val p: mut ref void = id.ptr as ref void+ @free(p)+ }+ }+ @listfree(ids)+}++fn reverse_lookup(map: oidmap.OidMap, id: objid.Id) option[bytes.Bytes] = trust {+ val i: mut usize = 0+ for i < map.cap {+ if oidmap.slot_used(map, i) {+ val value: bytes.Bytes = oidmap.slot_value(map, i)+ val same: bool = bytes.Bytes.eql(+ bytes.Bytes.slice(value, 0, 32),+ bytes.bytes(id.ptr, 32)+ )+ if same {+ return some(bytes.Bytes.dup(oidmap.slot_oid(map, i)))+ }+ }+ i+++ }+ return none+}++fn map_put(map: mut oidmap.OidMap, git_oid: bytes.Bytes, id: objid.Id) void = trust {+ oidmap.put(map, git_oid, bytes.bytes(id.ptr, 32))+}++fn hex_oid(oid: bytes.Bytes) ref u8 = trust {+ val out: ref u8 = @alloc(41) as ref u8+ objid.hex_encode(oid.ptr, 20, out)+ @store8(@ptradd(out, 40), 0)+ return out+}++fn object_path(repo: layout.Repo, oid: bytes.Bytes) str.StringView = trust {+ val hex: ref u8 = hex_oid(oid)+ val gitp: str.StringView = layout.git_dir(repo)+ val objects: str.StringView = files.join(gitp, str.from_cstr(c"objects"))+ val dirname: str.StringView = str.view(hex, 2)+ val filename: str.StringView = str.view(@ptradd(hex, 2), 38)+ val dir: str.StringView = files.join(objects, dirname)+ val path: str.StringView = files.join(dir, filename)+ files.free_path(dir)+ files.free_path(objects)+ files.free_path(gitp)+ @free(hex as ref void)+ return path+}++fn put_decimal(b: mut buf.Buf, v: u64) void = trust {+ if v == 0 {+ buf.Buf.put_u8(b, 48)+ return+ }+ val tmp: ref u8 = @alloc(24) as ref u8+ val n: mut usize = 0+ val x: mut u64 = v+ for x > 0 {+ @store8(@ptradd(tmp, n as i64), (48 + (x % 10)) as u8)+ x = x / 10+ n+++ }+ val i: mut usize = n+ for i > 0 {+ i--+ buf.Buf.put_u8(b, @load8(@ptradd(tmp, i as i64)))+ }+ @free(tmp as ref void)+}++fn kind_name(kind: u8) bytes.Bytes = trust {+ if kind == object.KIND_COMMIT {+ return bytes.bytes(c"commit", 6)+ }+ if kind == object.KIND_TREE {+ return bytes.bytes(c"tree", 4)+ }+ if kind == object.KIND_BLOB {+ return bytes.bytes(c"blob", 4)+ }+ return bytes.bytes(c"tag", 3)+}++fn write_loose(+ ctx: ref ExportCtx,+ kind: u8,+ oid: bytes.Bytes,+ body: bytes.Bytes+) bool = trust {+ val final: str.StringView = object_path(ctx.repo, oid)+ if files.exists_file(final) {+ files.free_path(final)+ return true+ }+ val hex: ref u8 = hex_oid(oid)+ val gitp: str.StringView = layout.git_dir(ctx.repo)+ val objects: str.StringView = files.join(gitp, str.from_cstr(c"objects"))+ val dirname: str.StringView = str.view(hex, 2)+ val objdir: str.StringView = files.join(objects, dirname)+ if !files.exists_dir(objdir) {+ val _ = files.mkdir_all(objdir)+ }+ files.free_path(objdir)+ files.free_path(objects)+ files.free_path(gitp)+ @free(hex as ref void)++ val header: mut buf.Buf = buf.new(64)+ buf.Buf.put_bytes(header, kind_name(kind))+ buf.Buf.put_u8(header, 32)+ put_decimal(header, body.len as u64)+ buf.Buf.put_u8(header, 0)+ buf.Buf.put_bytes(header, body)++ val bound: u64 = compressBound(header.len as u64)+ val dst: ref u8 = @alloc(bound as usize) as ref u8+ val dst_len: mut u64 = bound+ val rc: i32 = compress2(+ dst,+ dst_len,+ header.ptr,+ header.len as u64,+ 6+ )+ buf.Buf.free(header)+ if rc != 0 {+ @free(dst as ref void)+ files.free_path(final)+ return false+ }+ val tmpd: str.StringView = layout.tmp_dir(ctx.repo)+ val tmpname: str.StringView = files.basename(final)+ val tmp: str.StringView = files.join(tmpd, tmpname)+ val parent: str.StringView = files.join(layout.git_dir(ctx.repo), str.from_cstr(c"objects"))+ val good: bool = nativeio.write_atomic(+ tmp,+ final,+ tmpd,+ parent,+ bytes.bytes(dst, dst_len as usize)+ )+ files.free_path(tmp)+ files.free_path(tmpd)+ files.free_path(parent)+ files.free_path(final)+ @free(dst as ref void)+ return good+}++fn export_blob(ctx: mut ExportCtx, id: objid.Id) option[bytes.Bytes] = trust {+ if lazy.is_lazy(id) {+ val oid: bytes.Bytes = bytes.Bytes.dup(lazy.git_oid(id))+ map_put(ctx.blobs, oid, id)+ return some oid+ }+ val existing = reverse_lookup(ctx.blobs, id)+ if existing is some oid {+ return some oid+ }+ val data_opt = content.read_blob(ctx.handles, id, ctx.git, ctx.git_open)+ val data: mut bytes.Bytes = bytes.empty()+ match data_opt {+ some d => {+ data = d+ }+ none => {+ ctx.failed = true+ return none+ }+ }+ val hash = object.object_hash(object.KIND_BLOB, data)+ val oid: mut bytes.Bytes = bytes.empty()+ match hash {+ some h => {+ oid = h+ }+ none => {+ ctx.failed = true+ files.free_buffer(data)+ return none+ }+ }+ val wrote: bool = write_loose(ctx, object.KIND_BLOB, oid, data)+ files.free_buffer(data)+ if !wrote {+ ctx.failed = true+ object.free_digest(oid)+ return none+ }+ map_put(ctx.blobs, oid, id)+ return some oid+}++fn entry_key(e: ref tree.TreeEntry) bytes.Bytes = trust {+ // Git compares tree names as if directory names ended in '/'.+ if e.kind == tree.KIND_SUBTREE {+ val out: ref u8 = @alloc(e.name.len + 1) as ref u8+ @memcpy(out as ref void, e.name.ptr as ref void, e.name.len)+ @store8(@ptradd(out, e.name.len as i64), 47)+ return bytes.bytes(out, e.name.len + 1)+ }+ return e.name+}++fn sort_git_entries(entries: mut list[ref tree.TreeEntry]) void = trust {+ val i: mut usize = 1+ for i < @len(entries) {+ val cur = @get(entries, i)+ val c: mut ref tree.TreeEntry = none+ if cur is some v {+ c = v+ }+ val j: mut usize = i+ for j > 0 {+ val prev_o = @get(entries, j - 1)+ val prev: mut ref tree.TreeEntry = none+ if prev_o is some p {+ prev = p+ }+ val ck: bytes.Bytes = entry_key(c)+ val pk: bytes.Bytes = entry_key(prev)+ val cmp: i64 = bytes.Bytes.cmp(pk, ck)+ if pk.len > prev.name.len {+ val pp: mut ref void = pk.ptr as ref void+ @free(pp)+ }+ if ck.len > c.name.len {+ val cp: mut ref void = ck.ptr as ref void+ @free(cp)+ }+ if cmp <= 0 {+ break+ }+ @set(entries, j, prev)+ j--+ }+ @set(entries, j, c)+ i+++ }+}++fn mode_for(kind: u8) bytes.Bytes = trust {+ if kind == tree.KIND_EXECUTABLE {+ return bytes.bytes(c"100755", 6)+ }+ if kind == tree.KIND_SYMLINK {+ return bytes.bytes(c"120000", 6)+ }+ if kind == tree.KIND_SUBTREE {+ return bytes.bytes(c"40000", 5)+ }+ if kind == tree.KIND_SUBMODULE {+ return bytes.bytes(c"160000", 6)+ }+ return bytes.bytes(c"100644", 6)+}++fn export_tree(ctx: mut ExportCtx, id: objid.Id) option[bytes.Bytes] = trust {+ if ctx.failed {+ return none+ }+ val existing = reverse_lookup(ctx.trees, id)+ if existing is some oid {+ return some oid+ }+ val raw_opt = gitmap.load_raw(ctx.repo, id)+ if raw_opt is some raw {+ val hash = object.object_hash(object.KIND_TREE, raw)+ val oid: mut bytes.Bytes = bytes.empty()+ match hash {+ some h => {+ oid = h+ }+ none => {+ files.free_buffer(raw)+ ctx.failed = true+ return none+ }+ }+ val wrote: bool = write_loose(ctx, object.KIND_TREE, oid, raw)+ files.free_buffer(raw)+ if !wrote {+ ctx.failed = true+ object.free_digest(oid)+ return none+ }+ map_put(ctx.trees, oid, id)+ return some oid+ }+ val t_opt = treewalk.read_tree(ctx.handles, id)+ val t: mut ref tree.Tree = none+ match t_opt {+ some x => {+ t = x+ }+ none => {+ ctx.failed = true+ return none+ }+ }+ val entries: mut list[ref tree.TreeEntry] = lists.new[ref tree.TreeEntry]()+ val child_oids: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()+ val good: mut bool = true+ for e in t.entries {+ val child: mut option[bytes.Bytes] = none+ if e.kind == tree.KIND_SUBTREE {+ child = export_tree(ctx, e.target)+ } elif e.kind == tree.KIND_SUBMODULE {+ val oid20: bytes.Bytes = bytes.Bytes.dup(bytes.Bytes.slice(+ bytes.bytes(e.target.ptr, 32),+ 0,+ 20+ ))+ child = some(oid20)+ } elif e.kind == tree.KIND_CONFLICT {+ ctx.failed = true+ good = false+ } else {+ child = export_blob(ctx, e.target)+ }+ if child is some co {+ @append(+ entries,+ tree.entry(bytes.Bytes.dup(e.name), e.kind, objid.id(co.ptr))+ )+ @append(child_oids, co)+ } else {+ good = false+ }+ if !good {+ break+ }+ }+ tree.free_tree(t)+ if !good {+ for e in entries {+ if e.name.ptr != none {+ val np: mut ref void = e.name.ptr as ref void+ @free(np)+ }+ if e.target.ptr != none {+ val tp: mut ref void = e.target.ptr as ref void+ @free(tp)+ }+ val ep: mut ref void = e as ref void+ @free(ep)+ }+ @listfree(entries)+ for o in child_oids {+ object.free_digest(o)+ }+ @listfree(child_oids)+ return none+ }+ sort_git_entries(entries)+ val body: mut buf.Buf = buf.new(@len(entries) * 32 + 8)+ val i: mut usize = 0+ for i < @len(entries) {+ val o = @get(entries, i)+ if o is some e {+ buf.Buf.put_bytes(body, mode_for(e.kind))+ buf.Buf.put_u8(body, 32)+ buf.Buf.put_bytes(body, e.name)+ buf.Buf.put_u8(body, 0)+ buf.Buf.put_bytes(body, bytes.bytes(e.target.ptr, 20))+ }+ i+++ }+ val hash = object.object_hash(object.KIND_TREE, buf.Buf.view(body))+ val oid_out: mut bytes.Bytes = bytes.empty()+ match hash {+ some h => {+ oid_out = h+ }+ none => {+ good = false+ }+ }+ if good {+ good = write_loose(ctx, object.KIND_TREE, oid_out, buf.Buf.view(body))+ if good {+ map_put(ctx.trees, oid_out, id)+ }+ }+ buf.Buf.free(body)+ for e in entries {+ if e.name.ptr != none {+ val np: mut ref void = e.name.ptr as ref void+ @free(np)+ }+ if e.target.ptr != none {+ val tp: mut ref void = e.target.ptr as ref void+ @free(tp)+ }+ val ep: mut ref void = e as ref void+ @free(ep)+ }+ @listfree(entries)+ for o in child_oids {+ object.free_digest(o)+ }+ @listfree(child_oids)+ if !good {+ ctx.failed = true+ if oid_out.ptr != none {+ object.free_digest(oid_out)+ }+ return none+ }+ return some oid_out+}++fn parent_oids(ctx: mut ExportCtx, c: ref commit.Commit) list[bytes.Bytes] = trust {+ val out: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()+ for p in c.parents {+ val g = reverse_lookup(ctx.commits, p)+ match g {+ some oid => {+ @append(out, oid)+ }+ none => {+ ctx.failed = true+ }+ }+ }+ return out+}++fn serialize_commit(+ ctx: ref ExportCtx,+ id: objid.Id,+ c: ref commit.Commit,+ tree_oid: bytes.Bytes,+ parents: list[bytes.Bytes],+ is_native: bool+) option[bytes.Bytes] = trust {+ val raw_opt = gitmap.load_raw(ctx.repo, id)+ if raw_opt is some raw {+ val parsed_opt = format.parse_commit(raw)+ val use_raw: mut bool = false+ if parsed_opt is some parsed {+ if bytes.Bytes.eql(parsed.tree, tree_oid) && @len(parsed.parents) == @len(parents) {+ use_raw = true+ val pi: mut usize = 0+ for pi < @len(parents) {+ val po = @get(parsed.parents, pi)+ if po is some poid {+ if !bytes.Bytes.eql(poid, parents_at(parents, pi)) {+ use_raw = false+ break+ }+ }+ pi+++ }+ }+ format.free_parsed_commit(parsed)+ }+ if use_raw {+ return some raw+ }+ files.free_buffer(raw)+ }++ val extras: mut list[ref prim.KeyValue] = lists.new[ref prim.KeyValue]()+ for kv in c.extra {+ @append(extras, commit.new_kv(bytes.Bytes.dup(kv.key), bytes.Bytes.dup(kv.value)))+ }+ if is_native {+ val hex: ref u8 = objid.ChangeId.hex(c.change_id)+ @append(+ extras,+ commit.new_kv(+ bytes.Bytes.dup(bytes.bytes(c"veins-change-id", 15)),+ bytes.Bytes.dup(bytes.bytes(hex, 32))+ )+ )+ @free(hex as ref void)+ }+ val pc: mut ref format.ParsedCommit = @alloc(@sizeof(format.ParsedCommit)) as ref format.ParsedCommit+ pc.tree = tree_oid+ pc.parents = lists.new[bytes.Bytes]()+ for p in parents {+ @append(pc.parents, bytes.Bytes.dup(p))+ }+ pc.author = c.author+ pc.committer = c.committer+ pc.message = c.message+ pc.extras = extras+ pc.change_id = bytes.empty()+ pc.canonical = true+ val body: bytes.Bytes = format.serialize_commit(pc)+ // ParsedCommit owns parents/extras here, not the borrowed commit fields.+ for p in pc.parents {+ if p.ptr != none {+ val pp: mut ref void = p.ptr as ref void+ @free(pp)+ }+ }+ @listfree(pc.parents)+ for kv in extras {+ if kv.key.ptr != none {+ val kp: mut ref void = kv.key.ptr as ref void+ @free(kp)+ }+ if kv.value.ptr != none {+ val vp: mut ref void = kv.value.ptr as ref void+ @free(vp)+ }+ val xp: mut ref void = kv as ref void+ @free(xp)+ }+ @listfree(extras)+ @free(pc as ref void)+ return some body+}++fn parents_at(xs: list[bytes.Bytes], i: usize) bytes.Bytes = trust {+ val o = @get(xs, i)+ if o is some b {+ return b+ }+ return bytes.empty()+}++fn export_commit(ctx: mut ExportCtx, id: objid.Id) bool = trust {+ if ctx.failed {+ return false+ }+ val existing = reverse_lookup(ctx.commits, id)+ if existing is some _ {+ return true+ }+ val lc_opt = graph.load_commit(ctx.handles, id)+ val lc: mut ref graph.LoadedCommit = none+ match lc_opt {+ some x => {+ lc = x+ }+ none => {+ ctx.failed = true+ return false+ }+ }+ val tree_opt = export_tree(ctx, lc.c.root_tree)+ val tree_oid: mut bytes.Bytes = bytes.empty()+ match tree_opt {+ some t => {+ tree_oid = t+ }+ none => {+ graph.free_loaded(lc)+ return false+ }+ }+ val parents: list[bytes.Bytes] = parent_oids(ctx, lc.c)+ val is_native: bool = gitmap.is_native(ctx.native, id)+ val body_opt = serialize_commit(ctx, id, lc.c, tree_oid, parents, is_native)+ val body: mut bytes.Bytes = bytes.empty()+ match body_opt {+ some b => {+ body = b+ }+ none => {+ ctx.failed = true+ }+ }+ val status: mut bool = !ctx.failed+ val oid_out: mut bytes.Bytes = bytes.empty()+ if status {+ val hash = object.object_hash(object.KIND_COMMIT, body)+ match hash {+ some h => {+ oid_out = h+ }+ none => {+ status = false+ }+ }+ }+ if status {+ status = write_loose(ctx, object.KIND_COMMIT, oid_out, body)+ if status {+ map_put(ctx.commits, oid_out, id)+ }+ }+ if body.ptr != none {+ files.free_buffer(body)+ }+ if tree_oid.ptr != none {+ object.free_digest(tree_oid)+ }+ for p in parents {+ object.free_digest(p)+ }+ @listfree(parents)+ if oid_out.ptr != none {+ object.free_digest(oid_out)+ }+ graph.free_loaded(lc)+ if !status {+ ctx.failed = true+ }+ return status+}++fn ordered_commits(+ handles: list[ref store.Handle],+ roots: list[objid.Id]+) list[objid.Id] = trust {+ val all_ids: list[objid.Id] = graph.collect(handles, roots)+ val visited: mut list[objid.Id] = lists.new[objid.Id]()+ val ordered: mut list[objid.Id] = lists.new[objid.Id]()+ val stack: mut list[ref Mark] = lists.new[ref Mark]()+ val i0: mut usize = 0+ for i0 < @len(all_ids) {+ val o = @get(all_ids, i0)+ if o is some id {+ val m: mut ref Mark = @alloc(@sizeof(Mark)) as ref Mark+ m.id = id+ m.expanded = false+ @append(stack, m)+ }+ i0+++ }+ for @len(stack) > 0 {+ val m: mut ref Mark = @remove(stack, @len(stack) - 1)+ if contains(visited, m.id) {+ @free(m as ref void)+ continue+ }+ if !m.expanded {+ m.expanded = true+ @append(stack, m)+ val lc_opt = graph.load_commit(handles, m.id)+ if lc_opt is some lc {+ val pi: mut usize = @len(lc.c.parents)+ for pi > 0 {+ pi--+ val p = @get(lc.c.parents, pi)+ if p is some pid {+ if !contains(visited, pid) {+ val pm: mut ref Mark = @alloc(@sizeof(Mark)) as ref Mark+ pm.id = copy_id(pid)+ pm.expanded = false+ @append(stack, pm)+ }+ }+ }+ graph.free_loaded(lc)+ }+ } else {+ @append(visited, copy_id(m.id))+ @append(ordered, copy_id(m.id))+ @free(m as ref void)+ }+ }+ @listfree(stack)+ free_ids(visited)+ free_ids(all_ids)+ return ordered+}++fn exportable_target(handles: list[ref store.Handle], id: objid.Id) option[objid.Id] = trust {+ val current: mut objid.Id = copy_id(id)+ val steps: mut usize = 0+ for steps < 100000 {+ val lc_opt = graph.load_commit(handles, current)+ if lc_opt is none {+ if current.ptr != none {+ @free(current.ptr as ref void)+ }+ return none+ }+ val lc: mut ref graph.LoadedCommit = none+ if lc_opt is some x {+ lc = x+ }+ val conflicted: bool = treewalk.conflicted(handles, lc.c.root_tree)+ if !conflicted {+ val out: objid.Id = copy_id(current)+ graph.free_loaded(lc)+ if current.ptr != none {+ @free(current.ptr as ref void)+ }+ return some out+ }+ val next: mut option[objid.Id] = none+ if @len(lc.c.parents) > 0 {+ val p = @get(lc.c.parents, 0)+ if p is some pid {+ next = some(copy_id(pid))+ }+ }+ graph.free_loaded(lc)+ if current.ptr != none {+ @free(current.ptr as ref void)+ }+ match next {+ some nid => {+ current = nid+ }+ none => {+ return none+ }+ }+ steps+++ }+ return none+}++fn write_ref(ctx: ref ExportCtx, ref_name: bytes.Bytes, oid: bytes.Bytes) bool = trust {+ val gitp: str.StringView = layout.git_dir(ctx.repo)+ val refstr: str.StringView = files.to_view(ref_name)+ val final: str.StringView = files.join(gitp, refstr)+ val dir0: str.StringView = files.join(gitp, str.from_cstr(c"refs"))+ val dir: mut str.StringView = dir0+ val slash: mut i64 = -1+ val i: mut usize = 0+ for i < final.len {+ if @load8(@ptradd(final.ptr, i as i64)) == 47 {+ slash = i as i64+ }+ i+++ }+ if slash > 0 {+ dir = str.view(final.ptr, slash as usize)+ if !files.exists_dir(dir) {+ val _ = files.mkdir_all(dir)+ }+ }+ val hex: ref u8 = hex_oid(oid)+ val line: ref u8 = @fmtalloc("{s}\n", {str.from_cstr(hex)})+ val tmpd: str.StringView = layout.tmp_dir(ctx.repo)+ val tmpname: ref u8 = @fmtalloc("{s}.tmp", {str.from_cstr(hex)})+ val tmp_name_view: str.StringView = str.from_cstr(tmpname)+ val tmp: str.StringView = files.join(tmpd, tmp_name_view)+ val good: bool = nativeio.write_atomic(tmp, final, tmpd, dir, bytes.from_cstr(line))+ files.free_path(tmp)+ files.free_path(tmp_name_view)+ files.free_path(tmpd)+ files.free_path(dir0)+ files.free_path(final)+ files.free_path(gitp)+ @free(hex as ref void)+ @free(line as ref void)+ return good+}++pub fn run(repo: layout.Repo) i32 = trust {+ val gitp: str.StringView = layout.git_dir(repo)+ if !files.exists_dir(gitp) {+ msg.error_prefix()+ stdio.eprint("no git mirror; run `vn git import` first\n", {})+ files.free_path(gitp)+ return 1+ }+ val git_opt = object.open(gitp)+ files.free_path(gitp)+ val git_repo: mut object.GitRepo = @zeroed+ val git_open: mut bool = false+ match git_opt {+ ok g => {+ git_repo = g+ git_open = true+ }+ err _ => {+ }+ }++ val commits_opt = gitmap.load_map(repo, str.from_cstr(c"commits"))+ val trees_opt = gitmap.load_map(repo, str.from_cstr(c"trees"))+ val blobs_opt = gitmap.load_map(repo, str.from_cstr(c"blobs"))+ val commits: mut oidmap.OidMap = oidmap.new(64)+ val trees: mut oidmap.OidMap = oidmap.new(64)+ val blobs: mut oidmap.OidMap = oidmap.new(64)+ match commits_opt {+ ok m => {+ commits = m+ }+ err _ => {+ }+ }+ match trees_opt {+ ok m => {+ trees = m+ }+ err _ => {+ }+ }+ match blobs_opt {+ ok m => {+ blobs = m+ }+ err _ => {+ }+ }+ val native_ids: list[objid.Id] = gitmap.load_native(repo)+ val st: store.Store = store.open_all(repo)+ val ctx: mut ExportCtx = ExportCtx{+ repo: repo,+ handles: st.handles,+ commits: commits,+ trees: trees,+ blobs: blobs,+ native: native_ids,+ git: git_repo,+ git_open: git_open,+ failed: false+ }+ val v_opt = state.current_view(repo, st.handles)+ val v: mut ref view.View = none+ match v_opt {+ some x => {+ v = x+ }+ none => {+ store.close(st)+ oidmap.free(commits)+ oidmap.free(trees)+ oidmap.free(blobs)+ free_ids(native_ids)+ msg.error_prefix()+ stdio.eprint("no operation state\n", {})+ return 1+ }+ }+ val roots: mut list[objid.Id] = lists.new[objid.Id]()+ val resolved_bookmarks: mut list[ref view.Bookmark] = lists.new[ref view.Bookmark]()+ val mut_skipped: mut usize = 0+ for bm in v.bookmarks {+ val target = first_target(bm.targets.adds)+ if target is some tid {+ val exp = exportable_target(st.handles, tid)+ match exp {+ some x => {+ if !contains(roots, x) {+ @append(roots, copy_id(x))+ }+ val nb: mut ref view.Bookmark = @alloc(@sizeof(view.Bookmark)) as ref view.Bookmark+ nb.name = bytes.Bytes.dup(bm.name)+ nb.targets = view.empty_target_set()+ @append(nb.targets.adds, copy_id(x))+ @append(resolved_bookmarks, nb)+ if x.ptr != none {+ @free(x.ptr as ref void)+ }+ }+ none => {+ mut_skipped+++ }+ }+ }+ }+ val resolved_tags: mut list[ref view.TagRef] = lists.new[ref view.TagRef]()+ for t in v.tags {+ val exp = exportable_target(st.handles, t.target)+ match exp {+ some x => {+ if !contains(roots, x) {+ @append(roots, copy_id(x))+ }+ val nt: mut ref view.TagRef = @alloc(@sizeof(view.TagRef)) as ref view.TagRef+ nt.name = bytes.Bytes.dup(t.name)+ nt.target = copy_id(x)+ @append(resolved_tags, nt)+ if x.ptr != none {+ @free(x.ptr as ref void)+ }+ }+ none => {+ mut_skipped+++ }+ }+ }+ val ordered: list[objid.Id] = ordered_commits(st.handles, roots)+ val exported: mut usize = 0+ for id in ordered {+ val had = reverse_lookup(commits, id)+ if had is none {+ if export_commit(ctx, id) {+ exported+++ }+ } else {+ if had is some oid {+ object.free_digest(oid)+ }+ }+ if ctx.failed {+ break+ }+ }+ val status: mut i32 = 0+ if ctx.failed {+ msg.error_prefix()+ stdio.eprint("git export failed\n", {})+ status = 1+ } else {+ for bm in resolved_bookmarks {+ val target = first_target(bm.targets.adds)+ if target is some tid {+ val g = reverse_lookup(commits, tid)+ if g is some oid {+ val full: ref u8 = @alloc(11 + bm.name.len + 1) as ref u8+ @memcpy(full as ref void, c"refs/heads/", 11)+ @memcpy(@ptradd(full, 11) as ref void, bm.name.ptr as ref void, bm.name.len)+ @store8(@ptradd(full, (11 + bm.name.len) as i64), 0)+ val full_b: bytes.Bytes = bytes.from_cstr(full)+ if !write_ref(ctx, full_b, oid) {+ status = 1+ }+ @free(full as ref void)+ object.free_digest(oid)+ }+ }+ }+ for t in resolved_tags {+ val g = reverse_lookup(commits, t.target)+ if g is some oid {+ val full: ref u8 = @alloc(10 + t.name.len + 1) as ref u8+ @memcpy(full as ref void, c"refs/tags/", 10)+ @memcpy(@ptradd(full, 10) as ref void, t.name.ptr as ref void, t.name.len)+ @store8(@ptradd(full, (10 + t.name.len) as i64), 0)+ val full_b: bytes.Bytes = bytes.from_cstr(full)+ if !write_ref(ctx, full_b, oid) {+ status = 1+ }+ @free(full as ref void)+ object.free_digest(oid)+ }+ }+ if mut_skipped > 0 {+ msg.warning_prefix()+ stdio.eprint("skipped {d} conflicted ref(s)\n", {mut_skipped})+ }+ }+ if status == 0 {+ val sc = gitmap.save_map(repo, str.from_cstr(c"commits"), commits)+ val stree = gitmap.save_map(repo, str.from_cstr(c"trees"), trees)+ val sblob = gitmap.save_map(repo, str.from_cstr(c"blobs"), blobs)+ if !sc || !stree || !sblob {+ msg.error_prefix()+ stdio.eprint("failed to write git mapping tables\n", {})+ status = 1+ }+ }+ msg.info_prefix()+ stdio.print("exported {d} commits\n", {exported})+ view.free_view(v)+ free_ids(roots)+ free_ids(ordered)+ for bm in resolved_bookmarks {+ if bm.name.ptr != none {+ val np: mut ref void = bm.name.ptr as ref void+ @free(np)+ }+ for x in bm.targets.adds {+ if x.ptr != none {+ val xp: mut ref void = x.ptr as ref void+ @free(xp)+ }+ }+ for x in bm.targets.removes {+ if x.ptr != none {+ val xp2: mut ref void = x.ptr as ref void+ @free(xp2)+ }+ }+ @listfree(bm.targets.adds)+ @listfree(bm.targets.removes)+ val bp: mut ref void = bm as ref void+ @free(bp)+ }+ @listfree(resolved_bookmarks)+ for t in resolved_tags {+ if t.name.ptr != none {+ val np: mut ref void = t.name.ptr as ref void+ @free(np)+ }+ if t.target.ptr != none {+ val tp: mut ref void = t.target.ptr as ref void+ @free(tp)+ }+ val xp: mut ref void = t as ref void+ @free(xp)+ }+ @listfree(resolved_tags)+ free_ids(native_ids)+ store.close(st)+ oidmap.free(commits)+ oidmap.free(trees)+ oidmap.free(blobs)+ if git_open {+ object.free(git_repo)+ }+ return status+}++fn first_target(adds: list[objid.Id]) option[objid.Id] = trust {+ if @len(adds) > 0 {+ return @get(adds, 0)+ }+ return none+}--- /dev/null+++ b/veins/src/git/format.sx@@ -0,0 +1,656 @@+/// Parsing and canonical serialization of git commit, tree, and tag objects.++val bytes = use("../core/bytes.sx")+val buf = use("../core/buf.sx")+val prim = use("../core/primitives.sx")+val lists = use("../core/lists.sx")+val tree = use("../object/tree.sx")+val object = use("object.sx")++pub type RawTreeEntry = {+ mode: mut bytes.Bytes+ name: mut bytes.Bytes+ oid: mut bytes.Bytes+ canonical: mut bool+}++pub type ParsedTree = {+ entries: mut list[ref RawTreeEntry]+ canonical: mut bool+}++pub type ParsedTag = {+ target: mut bytes.Bytes+ target_kind: mut u8+}++pub type ParsedCommit = {+ tree: mut bytes.Bytes+ parents: mut list[bytes.Bytes]+ author: mut prim.Sig+ committer: mut prim.Sig+ message: mut bytes.Bytes+ extras: mut list[ref prim.KeyValue]+ change_id: mut bytes.Bytes+ canonical: mut bool+}++fn hex_digit(n: u8) u8 = trust {+ if n < 10 {+ return (48 + n) as u8+ }+ return (87 + n) as u8+}++fn hex_value(c: u8) i32 = trust {+ 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+}++pub fn oid_from_hex(hex: bytes.Bytes) option[bytes.Bytes] = trust {+ if hex.len != 40 {+ return none+ }+ val out: ref u8 = @alloc(20) as ref u8+ val i: mut usize = 0+ for i < 20 {+ val hi: i32 = hex_value(bytes.Bytes.at(hex, i * 2))+ val lo: i32 = hex_value(bytes.Bytes.at(hex, i * 2 + 1))+ if hi < 0 || lo < 0 {+ @free(out as ref void)+ return none+ }+ @store8(@ptradd(out, i as i64), ((hi * 16 + lo) as u8))+ i+++ }+ return some bytes.bytes(out, 20)+}++fn put_hex_id(b: mut buf.Buf, oid: bytes.Bytes) void = trust {+ val i: mut usize = 0+ for i < 20 {+ val v: u8 = bytes.Bytes.at(oid, i)+ buf.Buf.put_u8(b, hex_digit(v >> 4))+ buf.Buf.put_u8(b, hex_digit(v & 15))+ i+++ }+}++fn parse_u64(text: bytes.Bytes) option[u64] = trust {+ if text.len == 0 {+ return none+ }+ val v: mut u64 = 0+ val i: mut usize = 0+ for i < text.len {+ val c: u8 = bytes.Bytes.at(text, i)+ if c < 48 || c > 57 {+ return none+ }+ v = v * 10 + (c - 48) as u64+ i+++ }+ return some v+}++fn parse_i64(text: bytes.Bytes) option[i64] = trust {+ if text.len == 0 {+ return none+ }+ val negative: bool = bytes.Bytes.at(text, 0) == 45+ val start: mut usize = 0+ if negative {+ start = 1+ }+ val mag_opt = parse_u64(bytes.Bytes.slice(text, start, text.len))+ val mag: mut u64 = 0+ match mag_opt {+ some v => {+ mag = v+ }+ none => {+ return none+ }+ }+ if mag > 9223372036854775807 {+ return none+ }+ val signed: mut i64 = mag as i64+ if negative {+ signed = 0 - signed+ }+ return some signed+}++fn parse_tz(text: bytes.Bytes) option[i16] = trust {+ if text.len != 5 {+ return none+ }+ val sign: u8 = bytes.Bytes.at(text, 0)+ if sign != 43 && sign != 45 {+ return none+ }+ val hours_opt = parse_u64(bytes.Bytes.slice(text, 1, 3))+ val mins_opt = parse_u64(bytes.Bytes.slice(text, 3, 5))+ val hours: mut u64 = 0+ val mins: mut u64 = 0+ match hours_opt {+ some v => {+ hours = v+ }+ none => {+ return none+ }+ }+ match mins_opt {+ some v => {+ mins = v+ }+ none => {+ return none+ }+ }+ val total: i64 = (hours * 60 + mins) as i64+ if total > 32767 {+ return none+ }+ val tz: mut i16 = total as i16+ if sign == 45 {+ tz = 0 - tz+ }+ return some tz+}++fn last_index_of(value: bytes.Bytes, needle: u8, end: usize) i64 = trust {+ val i: mut i64 = end as i64 - 1+ for i >= 0 {+ if bytes.Bytes.at(value, i as usize) == needle {+ return i+ }+ i--+ }+ return -1+}++/// Parse "Name <email> seconds timezone".+pub fn parse_sig(value: bytes.Bytes) option[prim.Sig] = trust {+ val tz_space: i64 = last_index_of(value, 32, value.len)+ if tz_space < 0 {+ return none+ }+ val sec_space: i64 = last_index_of(value, 32, tz_space as usize)+ if sec_space < 0 {+ return none+ }+ val sec_opt = parse_i64(bytes.Bytes.slice(value, sec_space as usize + 1, tz_space as usize))+ val tz_opt = parse_tz(bytes.Bytes.slice(value, tz_space as usize + 1, value.len))+ val seconds: mut i64 = 0+ val tz: mut i16 = 0+ match sec_opt {+ some v => {+ seconds = v+ }+ none => {+ return none+ }+ }+ match tz_opt {+ some v => {+ tz = v+ }+ none => {+ return none+ }+ }+ val ident: bytes.Bytes = bytes.Bytes.slice(value, 0, sec_space as usize)+ val lt: i64 = last_index_of(ident, 60, ident.len)+ if lt < 0 {+ return none+ }+ val gt: i64 = last_index_of(ident, 62, ident.len)+ if gt <= lt {+ return none+ }+ val name_end: usize = lt as usize+ val email_start: usize = lt as usize + 1+ val email_end: usize = gt as usize+ val raw_name: bytes.Bytes = bytes.Bytes.slice(ident, 0, name_end)+ val name: mut bytes.Bytes = raw_name+ if raw_name.len > 0 && bytes.Bytes.at(raw_name, raw_name.len - 1) == 32 {+ name = bytes.Bytes.slice(raw_name, 0, raw_name.len - 1)+ }+ return some prim.Sig{+ name: name,+ email: bytes.Bytes.slice(ident, email_start, email_end),+ seconds: seconds,+ tz_min: tz+ }+}++fn put_sig(b: mut buf.Buf, sig: prim.Sig) void = trust {+ buf.Buf.put_bytes(b, sig.name)+ buf.Buf.put_u8(b, 32)+ buf.Buf.put_u8(b, 60)+ buf.Buf.put_bytes(b, sig.email)+ buf.Buf.put_u8(b, 62)+ buf.Buf.put_u8(b, 32)+ val sec_text: ref u8 = @fmtalloc("{d}", {sig.seconds})+ buf.Buf.put_bytes(b, bytes.from_cstr(sec_text))+ @free(sec_text as ref void)+ buf.Buf.put_u8(b, 32)+ val minutes: i64 = sig.tz_min as i64+ val abs_min: mut i64 = minutes+ if minutes < 0 {+ buf.Buf.put_u8(b, 45)+ abs_min = -minutes+ } else {+ buf.Buf.put_u8(b, 43)+ }+ val hh: i64 = abs_min / 60+ val mm: i64 = abs_min % 60+ buf.Buf.put_u8(b, (48 + hh / 10) as u8)+ buf.Buf.put_u8(b, (48 + hh % 10) as u8)+ buf.Buf.put_u8(b, (48 + mm / 10) as u8)+ buf.Buf.put_u8(b, (48 + mm % 10) as u8)+}++fn find_blank_line(data: bytes.Bytes) i64 = trust {+ if data.len < 2 {+ return -1+ }+ val i: mut usize = 0+ for i + 1 < data.len {+ if bytes.Bytes.at(data, i) == 10 && bytes.Bytes.at(data, i + 1) == 10 {+ return i as i64+ }+ i+++ }+ return -1+}++fn starts_with_space(line: bytes.Bytes) bool = trust {+ return line.len > 0 && bytes.Bytes.at(line, 0) == 32+}++fn parse_header_line(line: bytes.Bytes) option[prim.KeyValue] = trust {+ val space: mut usize = 0+ for space < line.len && bytes.Bytes.at(line, space) != 32 {+ space+++ }+ if space == 0 || space >= line.len {+ return none+ }+ val key: bytes.Bytes = bytes.Bytes.slice(line, 0, space)+ val value: bytes.Bytes = bytes.Bytes.slice(line, space + 1, line.len)+ return some prim.KeyValue{key: key, value: value}+}++fn new_kv(key: bytes.Bytes, value: bytes.Bytes) ref prim.KeyValue = trust {+ val kv: mut ref prim.KeyValue = @alloc(@sizeof(prim.KeyValue)) as ref prim.KeyValue+ kv.key = key+ kv.value = value+ return kv+}++fn find_line_end(data: bytes.Bytes, start: usize, end: usize) usize = trust {+ val i: mut usize = start+ for i < end && bytes.Bytes.at(data, i) != 10 {+ i+++ }+ return i+}++pub fn parse_commit(body: bytes.Bytes) option[ref ParsedCommit] = trust {+ val blank: i64 = find_blank_line(body)+ if blank < 0 {+ return none+ }+ val header_end: usize = blank as usize+ val message: bytes.Bytes = bytes.Bytes.slice(body, header_end + 2, body.len)+ val out: mut ref ParsedCommit = @alloc(@sizeof(ParsedCommit)) as ref ParsedCommit+ out.tree = bytes.empty()+ out.parents = lists.new[bytes.Bytes]()+ out.author = prim.Sig{name: bytes.empty(), email: bytes.empty(), seconds: 0, tz_min: 0}+ out.committer = prim.Sig{name: bytes.empty(), email: bytes.empty(), seconds: 0, tz_min: 0}+ out.message = message+ out.extras = lists.new[ref prim.KeyValue]()+ out.change_id = bytes.empty()+ out.canonical = true++ val last_extra: mut ref prim.KeyValue = none+ val last_extra_start: mut usize = 0+ val pos: mut usize = 0+ for pos < header_end {+ val line_end: usize = find_line_end(body, pos, header_end)+ val line: bytes.Bytes = bytes.Bytes.slice(body, pos, line_end)+ if starts_with_space(line) {+ if last_extra == none {+ out.canonical = false+ } else {+ last_extra.value = bytes.Bytes.slice(body, last_extra_start, line_end)+ }+ } else {+ last_extra = none+ val kv_opt = parse_header_line(line)+ match kv_opt {+ some kv => {+ if bytes.Bytes.eql(kv.key, bytes.bytes(c"tree", 4)) {+ val oid_opt = oid_from_hex(kv.value)+ match oid_opt {+ some oid => {+ out.tree = oid+ }+ none => {+ out.canonical = false+ }+ }+ } elif bytes.Bytes.eql(kv.key, bytes.bytes(c"parent", 6)) {+ val oid_opt2 = oid_from_hex(kv.value)+ match oid_opt2 {+ some oid => {+ @append(out.parents, oid)+ }+ none => {+ out.canonical = false+ }+ }+ } elif bytes.Bytes.eql(kv.key, bytes.bytes(c"author", 6)) {+ val sig_opt = parse_sig(kv.value)+ match sig_opt {+ some sig => {+ out.author = sig+ }+ none => {+ out.canonical = false+ }+ }+ } elif bytes.Bytes.eql(kv.key, bytes.bytes(c"committer", 9)) {+ val sig_opt2 = parse_sig(kv.value)+ match sig_opt2 {+ some sig => {+ out.committer = sig+ }+ none => {+ out.canonical = false+ }+ }+ } elif bytes.Bytes.eql(kv.key, bytes.bytes(c"veins-change-id", 15)) {+ if kv.value.len == 32 {+ val cid: ref u8 = @alloc(16) as ref u8+ val j: mut usize = 0+ for j < 16 {+ val hi: i32 = hex_value(bytes.Bytes.at(kv.value, j * 2))+ val lo: i32 = hex_value(bytes.Bytes.at(kv.value, j * 2 + 1))+ if hi < 0 || lo < 0 {+ @free(cid as ref void)+ out.canonical = false+ break+ }+ @store8(@ptradd(cid, j as i64), ((hi * 16 + lo) as u8))+ j+++ }+ if j == 16 {+ out.change_id = bytes.bytes(cid, 16)+ }+ } else {+ out.canonical = false+ }+ } else {+ val extra: ref prim.KeyValue = new_kv(kv.key, kv.value)+ @append(out.extras, extra)+ last_extra = extra+ last_extra_start = pos + kv.key.len + 1+ }+ }+ none => {+ out.canonical = false+ }+ }+ }+ pos = line_end + 1+ }+ return some out+}++pub fn free_parsed_commit(c: ref ParsedCommit) void = trust {+ for p in c.parents {+ if p.ptr != none {+ val pp: mut ref void = p.ptr as ref void+ @free(pp)+ }+ }+ @listfree(c.parents)+ if c.change_id.ptr != none {+ @free(c.change_id.ptr as ref void)+ }+ for kv in c.extras {+ val kp: mut ref void = kv as ref void+ @free(kp)+ }+ @listfree(c.extras)+ @free(c as ref void)+}++pub fn serialize_commit(c: ref ParsedCommit) bytes.Bytes = trust {+ val b: mut buf.Buf = buf.new(c.message.len + 256)+ buf.Buf.put_bytes(b, bytes.bytes(c"tree ", 5))+ put_hex_id(b, c.tree)+ buf.Buf.put_u8(b, 10)+ for p in c.parents {+ buf.Buf.put_bytes(b, bytes.bytes(c"parent ", 7))+ put_hex_id(b, p)+ buf.Buf.put_u8(b, 10)+ }+ buf.Buf.put_bytes(b, bytes.bytes(c"author ", 7))+ put_sig(b, c.author)+ buf.Buf.put_u8(b, 10)+ buf.Buf.put_bytes(b, bytes.bytes(c"committer ", 10))+ put_sig(b, c.committer)+ buf.Buf.put_u8(b, 10)+ for kv in c.extras {+ buf.Buf.put_bytes(b, kv.key)+ buf.Buf.put_u8(b, 32)+ buf.Buf.put_bytes(b, kv.value)+ buf.Buf.put_u8(b, 10)+ }+ buf.Buf.put_u8(b, 10)+ buf.Buf.put_bytes(b, c.message)+ val out: bytes.Bytes = bytes.Bytes.dup(buf.Buf.view(b))+ buf.Buf.free(b)+ return out+}++pub fn canonical_commit_bytes(body: bytes.Bytes) option[bytes.Bytes] = trust {+ val parsed_opt = parse_commit(body)+ match parsed_opt {+ some c => {+ val out: bytes.Bytes = serialize_commit(c)+ val same: bool = bytes.Bytes.eql(out, body)+ free_parsed_commit(c)+ if !same {+ val op: mut ref void = out.ptr as ref void+ @free(op)+ return none+ }+ return some out+ }+ none => {+ return none+ }+ }+}++pub fn parse_tree(body: bytes.Bytes) option[ref ParsedTree] = trust {+ val out: mut ref ParsedTree = @alloc(@sizeof(ParsedTree)) as ref ParsedTree+ out.entries = lists.new[ref RawTreeEntry]()+ out.canonical = true+ val pos: mut usize = 0+ for pos < body.len {+ val mode_start: usize = pos+ for pos < body.len && bytes.Bytes.at(body, pos) != 32 {+ pos+++ }+ if pos >= body.len {+ out.canonical = false+ break+ }+ val mode: bytes.Bytes = bytes.Bytes.slice(body, mode_start, pos)+ pos+++ val name_start: usize = pos+ for pos < body.len && bytes.Bytes.at(body, pos) != 0 {+ pos+++ }+ if pos >= body.len {+ out.canonical = false+ break+ }+ val name: bytes.Bytes = bytes.Bytes.slice(body, name_start, pos)+ pos+++ if pos + 20 > body.len {+ out.canonical = false+ break+ }+ val oid: bytes.Bytes = bytes.Bytes.slice(body, pos, pos + 20)+ pos = pos + 20+ val e: mut ref RawTreeEntry = @alloc(@sizeof(RawTreeEntry)) as ref RawTreeEntry+ e.mode = mode+ e.name = name+ e.oid = oid+ e.canonical = canonical_mode(mode)+ if !e.canonical {+ out.canonical = false+ }+ @append(out.entries, e)+ }+ if pos != body.len {+ out.canonical = false+ }+ return some out+}++fn canonical_mode(mode: bytes.Bytes) bool = trust {+ if bytes.Bytes.eql(mode, bytes.bytes(c"100644", 6)) {+ return true+ }+ if bytes.Bytes.eql(mode, bytes.bytes(c"100755", 6)) {+ return true+ }+ if bytes.Bytes.eql(mode, bytes.bytes(c"120000", 6)) {+ return true+ }+ if bytes.Bytes.eql(mode, bytes.bytes(c"40000", 5)) {+ return true+ }+ if bytes.Bytes.eql(mode, bytes.bytes(c"160000", 6)) {+ return true+ }+ return false+}++pub fn mode_kind(mode: bytes.Bytes) u8 = trust {+ if bytes.Bytes.eql(mode, bytes.bytes(c"40000", 5))+ || bytes.Bytes.eql(mode, bytes.bytes(c"040000", 6)) {+ return tree.KIND_SUBTREE+ }+ if bytes.Bytes.eql(mode, bytes.bytes(c"120000", 6)) {+ return tree.KIND_SYMLINK+ }+ if bytes.Bytes.eql(mode, bytes.bytes(c"160000", 6)) {+ return tree.KIND_SUBMODULE+ }+ if bytes.Bytes.eql(mode, bytes.bytes(c"100755", 6)) {+ return tree.KIND_EXECUTABLE+ }+ return tree.KIND_FILE+}++fn entry_at(entries: list[ref RawTreeEntry], i: usize) mut ref RawTreeEntry = trust {+ val o = @get(entries, i)+ if o is some e {+ return e+ }+ assert false+ return none+}+++/// Sort entries by plain name (veins' tree order).+pub fn sort_raw_entries(entries: mut list[ref RawTreeEntry]) void = trust {+ val n: usize = @len(entries)+ val i: mut usize = 1+ for i < n {+ val cur = entry_at(entries, i)+ val j: mut usize = i+ for j > 0 {+ val prev = entry_at(entries, j - 1)+ if bytes.Bytes.cmp(prev.name, cur.name) <= 0 {+ break+ }+ @set(entries, j, prev)+ j--+ }+ @set(entries, j, cur)+ i+++ }+}++pub fn free_parsed_tree(t: ref ParsedTree) void = trust {+ for e in t.entries {+ val ep: mut ref void = e as ref void+ @free(ep)+ }+ @listfree(t.entries)+ @free(t as ref void)+}++pub fn parse_tag(body: bytes.Bytes) option[ParsedTag] = trust {+ val out: mut ref ParsedTag = @alloc(@sizeof(ParsedTag)) as ref ParsedTag+ out.target = bytes.empty()+ out.target_kind = 0+ val pos: mut usize = 0+ for pos < body.len {+ val line_end: usize = find_line_end(body, pos, body.len)+ val line: bytes.Bytes = bytes.Bytes.slice(body, pos, line_end)+ if line.len == 0 {+ break+ }+ val kv_opt = parse_header_line(line)+ if kv_opt is some kv {+ if bytes.Bytes.eql(kv.key, bytes.bytes(c"object", 6)) {+ val oid_opt = oid_from_hex(kv.value)+ if oid_opt is some oid {+ out.target = oid+ }+ } elif bytes.Bytes.eql(kv.key, bytes.bytes(c"type", 4)) {+ if bytes.Bytes.eql(kv.value, bytes.bytes(c"commit", 6)) {+ out.target_kind = object.KIND_COMMIT+ } elif bytes.Bytes.eql(kv.value, bytes.bytes(c"tree", 4)) {+ out.target_kind = object.KIND_TREE+ } elif bytes.Bytes.eql(kv.value, bytes.bytes(c"blob", 4)) {+ out.target_kind = object.KIND_BLOB+ } elif bytes.Bytes.eql(kv.value, bytes.bytes(c"tag", 3)) {+ out.target_kind = object.KIND_TAG+ }+ }+ }+ pos = line_end + 1+ }+ return some out+}++pub fn free_parsed_tag(t: ref ParsedTag) void = trust {+ if t.target.ptr != none {+ val tp: mut ref void = t.target.ptr as ref void+ @free(tp)+ }+ val tq: mut ref void = t as ref void+ @free(tq)+}--- /dev/null+++ b/veins/src/git/import.sx@@ -0,0 +1,1246 @@+lib "z"++/// Import a git object graph into the veins store and record an operation.++val str = use("std/string")+val stdio = use("std/stdio")+val msg = use("../core/msg.sx")+val os = use("std/os")+val time = use("std/time")+val bytes = use("../core/bytes.sx")+val buf = use("../core/buf.sx")+val lists = use("../core/lists.sx")+val prim = use("../core/primitives.sx")+val b3 = use("../crypto/blake3.sx")+val objid = use("../object/id.sx")+val types = use("../object/types.sx")+val tree = use("../object/tree.sx")+val commit = use("../object/commit.sx")+val operation = use("../object/operation.sx")+val view = use("../object/view.sx")+val layout = use("../store/layout.sx")+val store = use("../store/store.sx")+val writer = use("../store/writer.sx")+val state = use("../store/state.sx")+val files = use("../io/files.sx")+val object = use("object.sx")+val lazy = use("lazy.sx")+val format = use("format.sx")+val refs = use("refs.sx")+val oidmap = use("oidmap.sx")+val gitmap = use("map.sx")+++pub type ImportStats = {+ commits: mut usize+ trees: mut usize+ blobs: mut usize+}++type ImportNamedTarget = {+ name: mut bytes.Bytes+ oid: mut bytes.Bytes+}++type ImportCommitRec = {+ oid: mut bytes.Bytes+ body: mut bytes.Bytes+ parsed: mut ref format.ParsedCommit+}++type ImportRawSave = {+ id: mut objid.Id+ body: mut bytes.Bytes+}++type ImportCtx = {+ git: object.GitRepo+ commits_map: mut oidmap.OidMap+ trees_map: mut oidmap.OidMap+ blobs_map: mut oidmap.OidMap+ raw_saves: mut list[ref ImportRawSave]+ new_commits: mut usize+ new_trees: mut usize+ new_blobs: mut usize+ writer: mut ref writer.Writer+}++fn put_usize(map: mut oidmap.OidMap, oid: bytes.Bytes, value: usize) void = trust {+ val v: ref u8 = @alloc(8) as ref u8+ @store64(v as ref void, value as i64)+ oidmap.put(map, oid, bytes.bytes(v, 8))+ @free(v as ref void)+}++fn get_usize(map: oidmap.OidMap, oid: bytes.Bytes) option[usize] = trust {+ val got = oidmap.get(map, oid)+ match got {+ some v => {+ return some (@load64(v.ptr as ref void) as usize)+ }+ none => {+ return none+ }+ }+}++fn get_id(map: oidmap.OidMap, oid: bytes.Bytes) option[objid.Id] = trust {+ val got = oidmap.get(map, oid)+ match got {+ some v => {+ return some objid.id(v.ptr)+ }+ none => {+ return none+ }+ }+}++fn put_id(map: mut oidmap.OidMap, oid: bytes.Bytes, id: objid.Id) void = trust {+ oidmap.put(map, oid, bytes.bytes(id.ptr, 32))+}++fn dup_id(id: objid.Id) objid.Id = trust {+ val out: ref u8 = @alloc(32) as ref u8+ @memcpy(out as ref void, id.ptr as ref void, 32)+ return objid.id(out)+}++fn append_object(ctx: mut ImportCtx, kind: u8, body: bytes.Bytes) objid.Id = trust {+ return writer.add(ctx.writer, kind, body)+}++fn derive_change_id(oid: bytes.Bytes) objid.ChangeId = trust {+ val b: mut buf.Buf = buf.new(48)+ buf.Buf.put_raw(b, c"veins/change", 12)+ buf.Buf.put_bytes(b, oid)+ val out: ref u8 = @alloc(32) as ref u8+ b3.hash(b.ptr, b.len, out)+ buf.Buf.free(b)+ return objid.change_id(out)+}++fn peel_to_commit(git: object.GitRepo, start: bytes.Bytes) option[bytes.Bytes] = trust {+ val current: mut bytes.Bytes = bytes.Bytes.dup(start)+ for {+ val obj_opt = object.read_fast(git, current)+ val obj: mut object.Object = object.Object{+ kind: 0,+ body: bytes.empty(),+ alloc: bytes.empty()+ }+ match obj_opt {+ ok o => {+ obj = o+ }+ err _ => {+ val cp: mut ref void = current.ptr as ref void+ @free(cp)+ return none+ }+ }+ if obj.kind == object.KIND_COMMIT {+ object.free_object(obj)+ return some current+ }+ if obj.kind != object.KIND_TAG {+ object.free_object(obj)+ val cp2: mut ref void = current.ptr as ref void+ @free(cp2)+ return none+ }+ val parsed_opt = format.parse_tag(obj.body)+ val parsed: mut ref format.ParsedTag = none+ match parsed_opt {+ some t => {+ parsed = t+ }+ none => {+ object.free_object(obj)+ val cp3: mut ref void = current.ptr as ref void+ @free(cp3)+ return none+ }+ }+ val next: mut bytes.Bytes = bytes.empty()+ if parsed.target.ptr != none {+ next = bytes.Bytes.dup(parsed.target)+ }+ format.free_parsed_tag(parsed)+ object.free_object(obj)+ val cp4: mut ref void = current.ptr as ref void+ @free(cp4)+ if next.ptr == none {+ return none+ }+ current = next+ }+ return none+}++fn import_blob(ctx: mut ImportCtx, oid: bytes.Bytes) option[objid.Id] = trust {+ val existing = get_id(ctx.blobs_map, oid)+ if existing is some id {+ return some dup_id(id)+ }+ val id: objid.Id = lazy.blob_id(oid)+ put_id(ctx.blobs_map, oid, id)+ ctx.new_blobs+++ return some dup_id(id)+}++fn import_tree(ctx: mut ImportCtx, oid: bytes.Bytes) option[objid.Id] = trust {+ val existing = get_id(ctx.trees_map, oid)+ if existing is some id {+ return some dup_id(id)+ }+ val obj_opt = object.read_fast(ctx.git, oid)+ val obj: mut object.Object = object.Object{kind: 0, body: bytes.empty(), alloc: bytes.empty()}+ match obj_opt {+ ok o => {+ obj = o+ }+ err _ => {+ return none+ }+ }+ if obj.kind != object.KIND_TREE {+ object.free_object(obj)+ return none+ }+ val parsed_opt = format.parse_tree(obj.body)+ val parsed: mut ref format.ParsedTree = none+ match parsed_opt {+ some t => {+ parsed = t+ }+ none => {+ object.free_object(obj)+ return none+ }+ }+ format.sort_raw_entries(parsed.entries)+ val entries: mut list[ref tree.TreeEntry] = lists.new[ref tree.TreeEntry]()+ val failed: mut bool = false+ for e in parsed.entries {+ val kind: u8 = format.mode_kind(e.mode)+ val target: mut objid.Id = objid.id_none()+ if kind == tree.KIND_SUBTREE {+ val child = import_tree(ctx, e.oid)+ match child {+ some id => {+ target = id+ }+ none => {+ failed = true+ }+ }+ } elif kind == tree.KIND_SUBMODULE {+ val out: ref u8 = @alloc(32) as ref u8+ @memset(out as ref void, 0, 32)+ @memcpy(out as ref void, e.oid.ptr as ref void, 20)+ target = objid.id(out)+ } else {+ val child2 = import_blob(ctx, e.oid)+ match child2 {+ some id2 => {+ target = id2+ }+ none => {+ failed = true+ }+ }+ }+ if failed {+ break+ }+ @append(entries, tree.entry(bytes.Bytes.dup(e.name), kind, target))+ }+ if failed {+ for te in entries {+ if te.name.ptr != none {+ val np: mut ref void = te.name.ptr as ref void+ @free(np)+ }+ if te.target.ptr != none {+ val ip: mut ref void = te.target.ptr as ref void+ @free(ip)+ }+ val tp: mut ref void = te as ref void+ @free(tp)+ }+ @listfree(entries)+ format.free_parsed_tree(parsed)+ object.free_object(obj)+ return none+ }+ val body_opt = tree.encode(entries)+ val body: mut bytes.Bytes = bytes.empty()+ match body_opt {+ ok b => {+ body = b+ }+ err _ => {+ failed = true+ }+ }+ for te in entries {+ if te.name.ptr != none {+ val np2: mut ref void = te.name.ptr as ref void+ @free(np2)+ }+ if te.target.ptr != none {+ val ip2: mut ref void = te.target.ptr as ref void+ @free(ip2)+ }+ val tp2: mut ref void = te as ref void+ @free(tp2)+ }+ @listfree(entries)+ if failed {+ format.free_parsed_tree(parsed)+ object.free_object(obj)+ return none+ }+ val id: objid.Id = append_object(ctx, types.TREE, body)+ put_id(ctx.trees_map, oid, id)+ ctx.new_trees+++ if !parsed.canonical {+ val copy: bytes.Bytes = bytes.Bytes.dup(obj.body)+ val rsave: mut ref ImportRawSave = @alloc(@sizeof(ImportRawSave)) as ref ImportRawSave+ rsave.id = dup_id(id)+ rsave.body = copy+ @append(ctx.raw_saves, rsave)+ }+ val out2: objid.Id = dup_id(id)+ format.free_parsed_tree(parsed)+ object.free_object(obj)+ return some out2+}++fn add_branch_target(+ list: mut list[ref ImportNamedTarget],+ name: bytes.Bytes,+ oid: bytes.Bytes+) void = trust {+ val t: mut ref ImportNamedTarget = @alloc(@sizeof(ImportNamedTarget)) as ref ImportNamedTarget+ t.name = name+ t.oid = oid+ @append(list, t)+}++fn free_named_targets(xs: list[ref ImportNamedTarget]) void = trust {+ for t in xs {+ if t.oid.ptr != none {+ val op: mut ref void = t.oid.ptr as ref void+ @free(op)+ }+ val tp: mut ref void = t as ref void+ @free(tp)+ }+ @listfree(xs)+}++fn sort_bookmarks(xs: mut list[ref view.Bookmark]) void = trust {+ val n: usize = @len(xs)+ val i: mut usize = 1+ for i < n {+ val cur = @get(xs, i)+ val c: mut ref view.Bookmark = none+ if cur is some v {+ c = v+ }+ val j: mut usize = i+ for j > 0 {+ val prev_opt = @get(xs, j - 1)+ val prev: mut ref view.Bookmark = none+ if prev_opt is some v2 {+ prev = v2+ }+ if bytes.Bytes.cmp(prev.name, c.name) <= 0 {+ break+ }+ @set(xs, j, prev)+ j--+ }+ @set(xs, j, c)+ i+++ }+}++fn sort_tags(xs: mut list[ref view.TagRef]) void = trust {+ val n: usize = @len(xs)+ val i: mut usize = 1+ for i < n {+ val cur = @get(xs, i)+ val c: mut ref view.TagRef = none+ if cur is some v {+ c = v+ }+ val j: mut usize = i+ for j > 0 {+ val prev_opt = @get(xs, j - 1)+ val prev: mut ref view.TagRef = none+ if prev_opt is some v2 {+ prev = v2+ }+ if bytes.Bytes.cmp(prev.name, c.name) <= 0 {+ break+ }+ @set(xs, j, prev)+ j--+ }+ @set(xs, j, c)+ i+++ }+}++fn set_bookmark(v: mut ref view.View, name: bytes.Bytes, id: objid.Id) void = trust {+ val bi: mut usize = 0+ for bi < @len(v.bookmarks) {+ val bmo = @get(v.bookmarks, bi)+ if bmo is some bm {+ if bytes.Bytes.eql(bm.name, name) {+ @listfree(bm.targets.adds)+ @listfree(bm.targets.removes)+ val adds: mut list[objid.Id] = lists.new[objid.Id]()+ @append(adds, id)+ bm.targets.adds = adds+ bm.targets.removes = lists.new[objid.Id]()+ return+ }+ }+ bi+++ }+ val bm: mut ref view.Bookmark = @alloc(@sizeof(view.Bookmark)) as ref view.Bookmark+ bm.name = bytes.Bytes.dup(name)+ val adds2: mut list[objid.Id] = lists.new[objid.Id]()+ @append(adds2, id)+ bm.targets = view.TargetSet{adds: adds2, removes: lists.new[objid.Id]()}+ @append(v.bookmarks, bm)+}++fn set_tag(v: mut ref view.View, name: bytes.Bytes, id: objid.Id) void = trust {+ val ti: mut usize = 0+ for ti < @len(v.tags) {+ val to = @get(v.tags, ti)+ if to is some t {+ if bytes.Bytes.eql(t.name, name) {+ t.target = id+ return+ }+ }+ ti+++ }+ val t: mut ref view.TagRef = @alloc(@sizeof(view.TagRef)) as ref view.TagRef+ t.name = bytes.Bytes.dup(name)+ t.target = id+ @append(v.tags, t)+}++fn set_workspace(v: mut ref view.View, name: bytes.Bytes, id: objid.Id) void = trust {+ val wi: mut usize = 0+ for wi < @len(v.working_copies) {+ val wo = @get(v.working_copies, wi)+ if wo is some w {+ if bytes.Bytes.eql(w.workspace, name) {+ w.target = id+ return+ }+ }+ wi+++ }+ val w: mut ref view.WorkspaceRef = @alloc(@sizeof(view.WorkspaceRef)) as ref view.WorkspaceRef+ w.workspace = bytes.Bytes.dup(name)+ w.target = id+ @append(v.working_copies, w)+}++fn clear_view_view(v: mut ref view.View) void = trust {+ @listfree(v.heads)+ for bm in v.bookmarks {+ @listfree(bm.targets.adds)+ @listfree(bm.targets.removes)+ val bp: mut ref void = bm as ref void+ @free(bp)+ }+ @listfree(v.bookmarks)+ for t in v.tags {+ val tp: mut ref void = t as ref void+ @free(tp)+ }+ @listfree(v.tags)+ for rr in v.remote_refs {+ val rp: mut ref void = rr as ref void+ @free(rp)+ }+ @listfree(v.remote_refs)+ for w in v.working_copies {+ val wp: mut ref void = w as ref void+ @free(wp)+ }+ @listfree(v.working_copies)+ @free(v as ref void)+}++fn add_unique_head(heads: mut list[objid.Id], id: objid.Id) void = trust {+ for x in heads {+ if objid.Id.eql(x, id) {+ return+ }+ }+ @append(heads, id)+}++fn sort_head_ids(heads: mut list[objid.Id]) void = trust {+ val n: usize = @len(heads)+ val i: mut usize = 1+ for i < n {+ val cur = @get(heads, i)+ val cid: mut objid.Id = objid.id_none()+ if cur is some v {+ cid = v+ }+ val j: mut usize = i+ for j > 0 {+ val prev_opt = @get(heads, j - 1)+ val prev: mut objid.Id = objid.id_none()+ if prev_opt is some v2 {+ prev = v2+ }+ if objid.Id.cmp(prev, cid) <= 0 {+ break+ }+ @set(heads, j, prev)+ j--+ }+ @set(heads, j, cid)+ i+++ }+}++fn free_commit_records(recs: list[ref ImportCommitRec]) void = trust {+ for r in recs {+ if r.body.ptr != none {+ val bp: mut ref void = r.body.ptr as ref void+ @free(bp)+ }+ if r.oid.ptr != none {+ val op: mut ref void = r.oid.ptr as ref void+ @free(op)+ }+ format.free_parsed_commit(r.parsed)+ val rp: mut ref void = r as ref void+ @free(rp)+ }+ @listfree(recs)+}++fn free_raw_saves(xs: list[ref ImportRawSave]) void = trust {+ for r in xs {+ if r.body.ptr != none {+ val bp: mut ref void = r.body.ptr as ref void+ @free(bp)+ }+ if r.id.ptr != none {+ val ip: mut ref void = r.id.ptr as ref void+ @free(ip)+ }+ val rp: mut ref void = r as ref void+ @free(rp)+ }+ @listfree(xs)+}+++/// Flush object batches as packs during large imports to bound peak memory.+pub fn run(repo: layout.Repo) i32 = trust {+ val git_path: str.StringView = layout.git_dir(repo)+ val git_opt = object.open(git_path)+ val git: mut object.GitRepo = @zeroed+ match git_opt {+ ok g => {+ git = g+ }+ err _ => {+ files.free_path(git_path)+ msg.error_prefix()+ stdio.eprint("cannot open git mirror: {s}\n", {git_path})+ return 1+ }+ }++ val commits_map_opt = gitmap.load_map(repo, str.from_cstr(c"commits"))+ val trees_map_opt = gitmap.load_map(repo, str.from_cstr(c"trees"))+ val blobs_map_opt = gitmap.load_map(repo, str.from_cstr(c"blobs"))+ val commits_map: mut oidmap.OidMap = oidmap.new(64)+ val trees_map: mut oidmap.OidMap = oidmap.new(64)+ val blobs_map: mut oidmap.OidMap = oidmap.new(64)+ val maps_ok: mut bool = true+ match commits_map_opt {+ ok m => {+ commits_map = m+ }+ err _ => {+ maps_ok = false+ }+ }+ match trees_map_opt {+ ok m2 => {+ trees_map = m2+ }+ err _ => {+ maps_ok = false+ }+ }+ match blobs_map_opt {+ ok m3 => {+ blobs_map = m3+ }+ err _ => {+ maps_ok = false+ }+ }+ if !maps_ok {+ msg.error_prefix()+ stdio.eprint("corrupt git mapping table\n", {})+ object.free(git)+ return 1+ }++ val refset: refs.RefSet = refs.read(git.git_dir)+ val writer_opt = writer.open(repo)+ val wref: mut ref writer.Writer = none+ match writer_opt {+ some w => {+ wref = w+ }+ none => {+ msg.error_prefix()+ stdio.eprint("cannot create import pack\n", {})+ refs.free(refset)+ oidmap.free(commits_map)+ oidmap.free(trees_map)+ oidmap.free(blobs_map)+ object.free(git)+ return 1+ }+ }+ val ctx: mut ImportCtx = ImportCtx{+ git: git,+ commits_map: commits_map,+ trees_map: trees_map,+ blobs_map: blobs_map,+ raw_saves: lists.new[ref ImportRawSave](),+ new_commits: 0,+ new_trees: 0,+ new_blobs: 0,+ writer: wref+ }++ val branches: mut list[ref ImportNamedTarget] = lists.new[ref ImportNamedTarget]()+ val tags: mut list[ref ImportNamedTarget] = lists.new[ref ImportNamedTarget]()+ val tips: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()+ for b in refset.branches {+ val peeled = peel_to_commit(ctx.git, b.oid)+ if peeled is some c {+ add_branch_target(branches, b.name, c)+ @append(tips, bytes.Bytes.dup(c))+ }+ }+ for t in refset.tags {+ val peeled2 = peel_to_commit(ctx.git, t.oid)+ if peeled2 is some c2 {+ add_branch_target(tags, t.name, c2)+ @append(tips, bytes.Bytes.dup(c2))+ }+ }+ val head_commit: mut option[bytes.Bytes] = none+ if refset.head.len > 0 {+ val head_peeled = peel_to_commit(ctx.git, refset.head)+ head_commit = head_peeled+ if head_peeled is some h {+ @append(tips, bytes.Bytes.dup(h))+ }+ }++ val seen: mut oidmap.OidMap = oidmap.new(64)+ val records: mut list[ref ImportCommitRec] = lists.new[ref ImportCommitRec]()+ val stack: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()+ for t in tips {+ @append(stack, t)+ }+ @listfree(tips)+ val collect_failed: mut bool = false+ for @len(stack) > 0 {+ val last: usize = @len(stack) - 1+ val oid: bytes.Bytes = @remove(stack, last)+ if oidmap.contains(ctx.commits_map, oid) || oidmap.contains(seen, oid) {+ val cp: mut ref void = oid.ptr as ref void+ @free(cp)+ continue+ }+ oidmap.put(seen, oid, bytes.empty())+ val obj_opt = object.read_fast(ctx.git, oid)+ val obj: mut object.Object = object.Object{+ kind: 0,+ body: bytes.empty(),+ alloc: bytes.empty()+ }+ match obj_opt {+ ok o => {+ obj = o+ }+ err _ => {+ collect_failed = true+ val cp2: mut ref void = oid.ptr as ref void+ @free(cp2)+ continue+ }+ }+ if obj.kind != object.KIND_COMMIT {+ object.free_object(obj)+ val cp3: mut ref void = oid.ptr as ref void+ @free(cp3)+ continue+ }+ val body: bytes.Bytes = bytes.Bytes.dup(obj.body)+ object.free_object(obj)+ val parsed_opt = format.parse_commit(body)+ val parsed: mut ref format.ParsedCommit = none+ match parsed_opt {+ some p => {+ parsed = p+ }+ none => {+ collect_failed = true+ val bp: mut ref void = body.ptr as ref void+ @free(bp)+ val cp4: mut ref void = oid.ptr as ref void+ @free(cp4)+ continue+ }+ }+ val rec: mut ref ImportCommitRec = @alloc(@sizeof(ImportCommitRec)) as ref ImportCommitRec+ rec.oid = oid+ rec.body = body+ rec.parsed = parsed+ @append(records, rec)+ for parent in parsed.parents {+ @append(stack, bytes.Bytes.dup(parent))+ }+ }+ @listfree(stack)+ oidmap.free(seen)++ val n: usize = @len(records)+ val indegree: ref u32 = @alloc(n * 4 + 1) as ref u32+ @memset(indegree as ref void, 0, n * 4 + 1)+ val children: mut list[list[usize]] = lists.new[list[usize]]()+ val i0: mut usize = 0+ for i0 < n {+ @append(children, lists.new[usize]())+ i0+++ }+ val index_map: mut oidmap.OidMap = oidmap.new(64)+ val i1: mut usize = 0+ for i1 < n {+ val rec_opt = @get(records, i1)+ if rec_opt is some rec2 {+ put_usize(index_map, rec2.oid, i1)+ }+ i1+++ }+ val topo_failed: mut bool = false+ val i2: mut usize = 0+ for i2 < n {+ val rec_opt2 = @get(records, i2)+ if rec_opt2 is some rec3 {+ for parent in rec3.parsed.parents {+ if oidmap.contains(ctx.commits_map, parent) {+ continue+ }+ val idx_opt = get_usize(index_map, parent)+ match idx_opt {+ some pidx => {+ if pidx < n {+ val deg_ptr: ref u32 = @ptradd(+ indegree as ref void,+ (i2 * 4) as i64+ ) as ref u32+ @store32(deg_ptr, (@load32(deg_ptr) + 1) as i32)+ val child_list = @get(children, pidx)+ if child_list is some cl {+ @append(cl, i2)+ }+ }+ }+ none => {+ topo_failed = true+ }+ }+ }+ }+ i2+++ }+ val queue: mut list[usize] = lists.new[usize]()+ val order: mut list[usize] = lists.new[usize]()+ val i3: mut usize = 0+ for i3 < n {+ val deg_ptr2: ref u32 = @ptradd(indegree as ref void, (i3 * 4) as i64) as ref u32+ if @load32(deg_ptr2) == 0 {+ @append(queue, i3)+ }+ i3+++ }+ val qhead: mut usize = 0+ for qhead < @len(queue) {+ val cur_opt = @get(queue, qhead)+ val cur: mut usize = 0+ if cur_opt is some cv {+ cur = cv+ }+ qhead+++ @append(order, cur)+ val child_list_opt = @get(children, cur)+ if child_list_opt is some cl2 {+ for child in cl2 {+ val dp: ref u32 = @ptradd(indegree as ref void, (child * 4) as i64) as ref u32+ val d: u32 = @load32(dp) as u32+ if d > 0 {+ @store32(dp, (d - 1) as i32)+ if d - 1 == 0 {+ @append(queue, child)+ }+ }+ }+ }+ }+ @listfree(queue)+ if topo_failed || @len(order) != n {+ msg.error_prefix()+ stdio.eprint("git commit graph is incomplete or cyclic\n", {})+ for cl3 in children {+ @listfree(cl3)+ }+ @listfree(children)+ @free(indegree as ref void)+ oidmap.free(index_map)+ free_commit_records(records)+ free_named_targets(branches)+ free_named_targets(tags)+ if head_commit is some h2 {+ val hp: mut ref void = h2.ptr as ref void+ @free(hp)+ }+ refs.free(refset)+ free_raw_saves(ctx.raw_saves)+ oidmap.free(ctx.commits_map)+ oidmap.free(ctx.trees_map)+ oidmap.free(ctx.blobs_map)+ object.free(ctx.git)+ return 1+ }++ val build_failed: mut bool = false+ // Import trees and blobs in topological order so git delta bases are read+ // before the objects that depend on them.+ val ci: mut usize = 0+ for ci < @len(order) {+ val idx_opt = @get(order, ci)+ val tree_idx: mut usize = 0+ if idx_opt is some tv {+ tree_idx = tv+ }+ val rec_opt4 = @get(records, tree_idx)+ if rec_opt4 is some rec4 {+ val tr = import_tree(ctx, rec4.parsed.tree)+ if tr is none {+ build_failed = true+ break+ }+ if tr is some tid {+ val tp: mut ref void = tid.ptr as ref void+ @free(tp)+ }+ }+ ci+++ }++ val oi: mut usize = 0+ for oi < @len(order) {+ val idx_opt = @get(order, oi)+ val idx: mut usize = 0+ if idx_opt is some v {+ idx = v+ }+ val rec_opt3 = @get(records, idx)+ val rec: mut ref ImportCommitRec = none+ if rec_opt3 is some v2 {+ rec = v2+ }+ val tree_map = get_id(ctx.trees_map, rec.parsed.tree)+ val root_tree: mut objid.Id = objid.id_none()+ match tree_map {+ some t => {+ root_tree = t+ }+ none => {+ build_failed = true+ }+ }+ val parents: mut list[objid.Id] = lists.new[objid.Id]()+ for p in rec.parsed.parents {+ val pid = get_id(ctx.commits_map, p)+ match pid {+ some id => {+ @append(parents, id)+ }+ none => {+ build_failed = true+ }+ }+ }+ if build_failed {+ @listfree(parents)+ break+ }+ val cid: mut objid.ChangeId = objid.change_id(none)+ if rec.parsed.change_id.ptr != none {+ cid = objid.change_id(rec.parsed.change_id.ptr)+ } else {+ cid = derive_change_id(rec.oid)+ }+ val renames: list[ref commit.Rename] = lists.new[ref commit.Rename]()+ val c: mut ref commit.Commit = @alloc(@sizeof(commit.Commit)) as ref commit.Commit+ c.version = 1+ c.parents = parents+ c.root_tree = root_tree+ c.change_id = cid+ c.author = rec.parsed.author+ c.committer = rec.parsed.committer+ c.message = rec.parsed.message+ c.renames_state = commit.RENAMES_UNKNOWN+ c.renames = renames+ c.extra = rec.parsed.extras+ val cbody: bytes.Bytes = commit.encode(c)+ val cid_out: objid.Id = append_object(ctx, types.COMMIT, cbody)+ @listfree(c.parents)+ @listfree(c.renames)+ @free(c as ref void)+ put_id(ctx.commits_map, rec.oid, cid_out)+ ctx.new_commits+++ val serialized: bytes.Bytes = format.serialize_commit(rec.parsed)+ val is_canonical: bool = rec.parsed.canonical && bytes.Bytes.eql(serialized, rec.body)+ if serialized.ptr != none {+ val sp: mut ref void = serialized.ptr as ref void+ @free(sp)+ }+ if !is_canonical {+ val rsave: mut ref ImportRawSave = @alloc(@sizeof(ImportRawSave)) as ref ImportRawSave+ rsave.id = dup_id(cid_out)+ rsave.body = bytes.Bytes.dup(rec.body)+ @append(ctx.raw_saves, rsave)+ }+ if cid.ptr != none && rec.parsed.change_id.ptr == none {+ val cp5: mut ref void = cid.ptr as ref void+ @free(cp5)+ }+ oi+++ }+ @listfree(order)+ for cl4 in children {+ @listfree(cl4)+ }+ @listfree(children)+ @free(indegree as ref void)+ oidmap.free(index_map)++ if build_failed {+ msg.error_prefix()+ stdio.eprint("referenced git object is missing\n", {})+ free_commit_records(records)+ free_named_targets(branches)+ free_named_targets(tags)+ if head_commit is some h3 {+ val hp2: mut ref void = h3.ptr as ref void+ @free(hp2)+ }+ refs.free(refset)+ free_raw_saves(ctx.raw_saves)+ oidmap.free(ctx.commits_map)+ oidmap.free(ctx.trees_map)+ oidmap.free(ctx.blobs_map)+ object.free(ctx.git)+ return 1+ }++ if build_failed {+ msg.error_prefix()+ stdio.eprint("failed to import a tree or blob\n", {})+ free_commit_records(records)+ free_named_targets(branches)+ free_named_targets(tags)+ if head_commit is some h4 {+ val hp3: mut ref void = h4.ptr as ref void+ @free(hp3)+ }+ refs.free(refset)+ free_raw_saves(ctx.raw_saves)+ oidmap.free(ctx.commits_map)+ oidmap.free(ctx.trees_map)+ oidmap.free(ctx.blobs_map)+ object.free(ctx.git)+ return 1+ }++ // Load the current view and store.+ val store_handle: store.Store = store.open_all(repo)+ val current = state.current_view(repo, store_handle.handles)+ val v: mut ref view.View = none+ val old_encoded: mut bytes.Bytes = bytes.empty()+ match current {+ some cv => {+ v = cv+ old_encoded = view.encode(v)+ }+ none => {+ v = state.empty_view()+ }+ }++ for b in branches {+ val id = get_id(ctx.commits_map, b.oid)+ if id is some bid {+ set_bookmark(v, b.name, bid)+ }+ }+ for t in tags {+ val id = get_id(ctx.commits_map, t.oid)+ if id is some tid {+ set_tag(v, t.name, tid)+ }+ }+ sort_bookmarks(v.bookmarks)+ sort_tags(v.tags)++ @listfree(v.heads)+ val new_heads: mut list[objid.Id] = lists.new[objid.Id]()+ for b in branches {+ val id = get_id(ctx.commits_map, b.oid)+ if id is some bid {+ add_unique_head(new_heads, bid)+ }+ }+ if @len(new_heads) == 0 {+ for t in tags {+ val id = get_id(ctx.commits_map, t.oid)+ if id is some tid {+ add_unique_head(new_heads, tid)+ }+ }+ }+ val head_id: mut objid.Id = objid.id_none()+ if head_commit is some hc {+ val hcid = get_id(ctx.commits_map, hc)+ if hcid is some hv {+ head_id = hv+ }+ }+ if @len(new_heads) == 0 && !objid.Id.is_none(head_id) {+ add_unique_head(new_heads, head_id)+ }+ sort_head_ids(new_heads)+ v.heads = new_heads+ if !objid.Id.is_none(head_id) {+ set_workspace(v, bytes.bytes(c"default", 7), head_id)+ } elif @len(new_heads) > 0 {+ val first = @get(new_heads, 0)+ if first is some fid {+ set_workspace(v, bytes.bytes(c"default", 7), fid)+ }+ }++ val new_encoded: bytes.Bytes = view.encode(v)+ val unchanged: bool = bytes.Bytes.eql(old_encoded, new_encoded)+ val has_new_objects: bool = ctx.new_commits > 0 || ctx.new_trees > 0 || ctx.new_blobs > 0+ if unchanged && !has_new_objects {+ if old_encoded.ptr != none {+ val op: mut ref void = old_encoded.ptr as ref void+ @free(op)+ }+ if new_encoded.ptr != none {+ val np: mut ref void = new_encoded.ptr as ref void+ @free(np)+ }+ clear_view_view(v)+ free_commit_records(records)+ free_named_targets(branches)+ free_named_targets(tags)+ if head_commit is some h5 {+ val hp4: mut ref void = h5.ptr as ref void+ @free(hp4)+ }+ refs.free(refset)+ free_raw_saves(ctx.raw_saves)+ oidmap.free(ctx.commits_map)+ oidmap.free(ctx.trees_map)+ oidmap.free(ctx.blobs_map)+ store.close(store_handle)+ object.free(ctx.git)+ msg.info_prefix()+ stdio.print("already up to date\n", {})+ return 0+ }++ val view_id: objid.Id = append_object(ctx, types.VIEW, new_encoded)+ val parent_heads: list[objid.Id] = state.heads(repo)+ val op_parents: mut list[objid.Id] = lists.new[objid.Id]()+ for ph in parent_heads {+ @append(op_parents, ph)+ }+ @listfree(parent_heads)+ val now: i64 = time.unix_now_millis()+ val tm: prim.TimeMs = prim.TimeMs{ms: now, tz_min: 0}+ val hostname: bytes.Bytes = host_from_env()+ val username: bytes.Bytes = user_from_env()+ val op_tags: mut list[ref prim.KeyValue] = lists.new[ref prim.KeyValue]()+ val cmd_kv: mut ref prim.KeyValue = @alloc(@sizeof(prim.KeyValue)) as ref prim.KeyValue+ cmd_kv.key = bytes.bytes(c"command", 7)+ cmd_kv.value = bytes.bytes(c"git import", 10)+ @append(op_tags, cmd_kv)+ val op: mut ref operation.Operation = @alloc(@sizeof(operation.Operation)) as ref operation.Operation+ op.parents = op_parents+ op.view = view_id+ op.start = tm+ op.end = tm+ op.hostname = hostname+ op.username = username+ op.description = bytes.bytes(c"git import", 10)+ op.tags = op_tags+ val op_body: bytes.Bytes = operation.encode(op)+ val op_id: objid.Id = append_object(ctx, types.OPERATION, op_body)+ @listfree(op.tags)+ @free(op as ref void)+ if hostname.ptr != none {+ val hp5: mut ref void = hostname.ptr as ref void+ @free(hp5)+ }+ if username.ptr != none {+ val up: mut ref void = username.ptr as ref void+ @free(up)+ }++ val wrote: bool = writer.finish(ctx.writer)+ if !wrote {+ msg.error_prefix()+ stdio.eprint("failed to write object pack\n", {})+ if old_encoded.ptr != none {+ val op2: mut ref void = old_encoded.ptr as ref void+ @free(op2)+ }+ clear_view_view(v)+ for ph2 in op_parents {+ if ph2.ptr != none {+ val pp: mut ref void = ph2.ptr as ref void+ @free(pp)+ }+ }+ @listfree(op_parents)+ free_commit_records(records)+ free_named_targets(branches)+ free_named_targets(tags)+ if head_commit is some h6 {+ val hp6: mut ref void = h6.ptr as ref void+ @free(hp6)+ }+ refs.free(refset)+ free_raw_saves(ctx.raw_saves)+ oidmap.free(ctx.commits_map)+ oidmap.free(ctx.trees_map)+ oidmap.free(ctx.blobs_map)+ store.close(store_handle)+ object.free(ctx.git)+ return 1+ }++ for rs in ctx.raw_saves {+ val _ = gitmap.save_raw(repo, rs.id, rs.body)+ }+ val saved_commits: bool = gitmap.save_map(repo, str.from_cstr(c"commits"), ctx.commits_map)+ val saved_trees: bool = gitmap.save_map(repo, str.from_cstr(c"trees"), ctx.trees_map)+ val saved_blobs: bool = gitmap.save_map(repo, str.from_cstr(c"blobs"), ctx.blobs_map)+ if !saved_commits || !saved_trees || !saved_blobs {+ msg.error_prefix()+ stdio.eprint("failed to write git mapping tables\n", {})+ }+ val head_ok: bool = state.write_head(repo, op_id)+ if head_ok {+ for ph3 in op_parents {+ if !objid.Id.is_none(ph3) {+ val _ = state.delete_head(repo, ph3)+ }+ }+ }++ msg.info_prefix()+ stdio.print(+ "imported {d} commits, {d} trees, {d} blobs\n",+ {ctx.new_commits, ctx.new_trees, ctx.new_blobs}+ )++ if old_encoded.ptr != none {+ val op3: mut ref void = old_encoded.ptr as ref void+ @free(op3)+ }+ clear_view_view(v)+ for ph4 in op_parents {+ if ph4.ptr != none {+ val pp2: mut ref void = ph4.ptr as ref void+ @free(pp2)+ }+ }+ @listfree(op_parents)+ free_commit_records(records)+ free_named_targets(branches)+ free_named_targets(tags)+ if head_commit is some h7 {+ val hp7: mut ref void = h7.ptr as ref void+ @free(hp7)+ }+ refs.free(refset)+ free_raw_saves(ctx.raw_saves)+ oidmap.free(ctx.commits_map)+ oidmap.free(ctx.trees_map)+ oidmap.free(ctx.blobs_map)+ store.close(store_handle)+ object.free(ctx.git)+ if !head_ok {+ return 1+ }+ return 0+}++fn host_from_env() bytes.Bytes = trust {+ val h = os.env(c"HOSTNAME")+ match h {+ some v => {+ return bytes.Bytes.dup(bytes.from_cstr(v))+ }+ none => {+ return bytes.Bytes.dup(bytes.bytes(c"localhost", 9))+ }+ }+}++fn user_from_env() bytes.Bytes = trust {+ val u = os.env(c"USER")+ match u {+ some v => {+ return bytes.Bytes.dup(bytes.from_cstr(v))+ }+ none => {+ return bytes.Bytes.dup(bytes.bytes(c"unknown", 7))+ }+ }+}--- /dev/null+++ b/veins/src/git/lazy.sx@@ -0,0 +1,53 @@+/// Git-backed blob identifiers used by lazy imports.+///+/// A lazy blob ID is the 12-byte prefix "veins-gitoid" followed by the+/// 20-byte git object ID. Blob bodies stay in the `.veins/git` mirror until+/// they are materialized.++val bytes = use("../core/bytes.sx")+val objid = use("../object/id.sx")++pub val PREFIX_LEN: usize = 12+pub val GIT_OID_LEN: usize = 20+pub val ID_LEN: usize = 32++fn prefix() bytes.Bytes = {+ return bytes.bytes(c"veins-gitoid", 12)+}++/// Build the lazy veins ID for a git blob.+pub fn blob_id(oid: bytes.Bytes) objid.Id = trust {+ pre {+ oid_len: oid.len == GIT_OID_LEN+ }+ val out: ref u8 = @alloc(ID_LEN) as ref u8+ @memcpy(out as ref void, prefix().ptr as ref void, PREFIX_LEN)+ @memcpy(+ @ptradd(out, PREFIX_LEN as i64) as ref void,+ oid.ptr as ref void,+ GIT_OID_LEN+ )+ return objid.id(out)+}++/// True when `id` names a git-backed blob rather than a stored veins blob.+pub fn is_lazy(id: objid.Id) bool = trust {+ if id.ptr == none {+ return false+ }+ return bytes.Bytes.eql(+ bytes.bytes(id.ptr, PREFIX_LEN),+ prefix()+ )+}++/// The git object ID carried by a lazy blob ID. The result is borrowed.+pub fn git_oid(id: objid.Id) bytes.Bytes = trust {+ pre {+ present: id.ptr != none+ }+ return bytes.bytes(+ @ptradd(id.ptr, PREFIX_LEN as i64),+ GIT_OID_LEN+ )+}--- /dev/null+++ b/veins/src/git/map.sx@@ -0,0 +1,207 @@+/// Persistent git ID mapping tables and raw-object storage.++val str = use("std/string")+val bytes = use("../core/bytes.sx")+val lists = use("../core/lists.sx")+val buf = use("../core/buf.sx")+val objid = use("../object/id.sx")+val layout = use("../store/layout.sx")+val files = use("../io/files.sx")+val native = use("../io/native.sx")+val oidmap = use("oidmap.sx")+val object = use("object.sx")++pub fn map_path(repo: layout.Repo, name: str.StringView) str.StringView = {+ val dir: str.StringView = layout.git_map_dir(repo)+ val p: str.StringView = files.join(dir, name)+ files.free_path(dir)+ return p+}++fn map_name(base: str.StringView, suffix: str.StringView) str.StringView = {+ return files.with_suffix(base, suffix)+}++pub fn load_map(+ repo: layout.Repo,+ name: str.StringView+) result[oidmap.OidMap, object.GitError] = trust {+ val base: str.StringView = layout.git_map_dir(repo)+ val suffix: str.StringView = str.from_cstr(c".map")+ val fname: str.StringView = files.with_suffix(name, suffix)+ val path: str.StringView = files.join(base, fname)+ files.free_path(base)+ files.free_path(fname)+ val data_opt = files.read_all(path)+ files.free_path(path)+ val map: mut oidmap.OidMap = oidmap.new(64)+ val data: mut bytes.Bytes = bytes.empty()+ match data_opt {+ some d => {+ data = d+ }+ none => {+ return ok map+ }+ }+ if data.len < 9 || !bytes.Bytes.eql(bytes.Bytes.slice(data, 0, 5), bytes.bytes(c"VMAP1", 5)) {+ files.free_buffer(data)+ oidmap.free(map)+ return err object.GitError.Corrupt+ }+ val count: u32 = (bytes.Bytes.at(data, 5) as u32)+ | ((bytes.Bytes.at(data, 6) as u32) << 8)+ | ((bytes.Bytes.at(data, 7) as u32) << 16)+ | ((bytes.Bytes.at(data, 8) as u32) << 24)+ val need: u64 = 9 as u64 + (count as u64) * 52 as u64+ if need != data.len as u64 {+ files.free_buffer(data)+ oidmap.free(map)+ return err object.GitError.Corrupt+ }+ val i: mut usize = 0+ for i < count as usize {+ val off: usize = 9 + i * 52+ oidmap.put(+ map,+ bytes.Bytes.slice(data, off, off + 20),+ bytes.Bytes.slice(data, off + 20, off + 52)+ )+ i+++ }+ files.free_buffer(data)+ return ok map+}++pub fn save_map(repo: layout.Repo, name: str.StringView, map: oidmap.OidMap) bool = trust {+ val b: mut buf.Buf = buf.new(map.len * 52 + 16)+ buf.Buf.put_raw(b, c"VMAP1", 5)+ buf.Buf.put_u32_le(b, map.len as u32)+ val i: mut usize = 0+ for i < map.cap {+ if oidmap.slot_used(map, i) {+ buf.Buf.put_bytes(b, oidmap.slot_oid(map, i))+ buf.Buf.put_bytes(b, oidmap.slot_value(map, i))+ }+ i+++ }+ val base: str.StringView = layout.git_map_dir(repo)+ val suffix: str.StringView = str.from_cstr(c".map")+ val fname: str.StringView = files.with_suffix(name, suffix)+ val final: str.StringView = files.join(base, fname)+ val tmpd: str.StringView = layout.tmp_dir(repo)+ val tmpname: str.StringView = map_name(fname, str.from_cstr(c".tmp"))+ val tmp: str.StringView = files.join(tmpd, tmpname)+ val success: bool = native.write_atomic(tmp, final, tmpd, base, buf.Buf.view(b))+ files.free_path(base)+ files.free_path(tmpd)+ files.free_path(fname)+ files.free_path(final)+ files.free_path(tmpname)+ files.free_path(tmp)+ buf.Buf.free(b)+ return success+}++fn veins_hex(id: objid.Id) ref u8 = {+ return objid.Id.hex(id)+}++pub fn save_raw(repo: layout.Repo, id: objid.Id, body: bytes.Bytes) bool = trust {+ val hex: ref u8 = veins_hex(id)+ val base: str.StringView = layout.raw_dir(repo)+ val name: str.StringView = str.from_cstr(hex)+ val final: str.StringView = files.join(base, name)+ val tmpd: str.StringView = layout.tmp_dir(repo)+ val tmpname: str.StringView = files.with_suffix(name, str.from_cstr(c".tmp"))+ val tmp: str.StringView = files.join(tmpd, tmpname)+ val success: bool = native.write_atomic(tmp, final, tmpd, base, body)+ files.free_path(base)+ files.free_path(tmpd)+ files.free_path(final)+ files.free_path(tmpname)+ files.free_path(tmp)+ @free(hex as ref void)+ return success+}++pub fn has_raw(repo: layout.Repo, id: objid.Id) bool = trust {+ val hex: ref u8 = veins_hex(id)+ val base: str.StringView = layout.raw_dir(repo)+ val name: str.StringView = str.from_cstr(hex)+ val path: str.StringView = files.join(base, name)+ val found: bool = files.exists_file(path)+ files.free_path(base)+ files.free_path(path)+ @free(hex as ref void)+ return found+}++pub fn load_raw(repo: layout.Repo, id: objid.Id) option[bytes.Bytes] = trust {+ val hex: ref u8 = veins_hex(id)+ val base: str.StringView = layout.raw_dir(repo)+ val name: str.StringView = str.from_cstr(hex)+ val path: str.StringView = files.join(base, name)+ val data = files.read_all(path)+ files.free_path(base)+ files.free_path(path)+ @free(hex as ref void)+ return data+}++fn native_path(repo: layout.Repo) str.StringView = {+ val base: str.StringView = layout.git_map_dir(repo)+ val p: str.StringView = files.join(base, str.from_cstr(c"native"))+ files.free_path(base)+ return p+}++/// Remember that a commit was created natively so the exporter knows whether+/// to add the `veins-change-id` header.+pub fn mark_native(repo: layout.Repo, id: objid.Id) bool = trust {+ val hex: ref u8 = objid.Id.hex(id)+ val line: ref u8 = @fmtalloc("{s}\n", {str.from_cstr(hex)})+ val p: str.StringView = native_path(repo)+ val appended: bool = files.append_all(p, bytes.from_cstr(line))+ files.free_path(p)+ @free(hex as ref void)+ @free(line as ref void)+ return appended+}++pub fn load_native(repo: layout.Repo) list[objid.Id] = trust {+ val out: mut list[objid.Id] = lists.new[objid.Id]()+ val p: str.StringView = native_path(repo)+ val data_opt = files.read_all(p)+ files.free_path(p)+ if data_opt is some data {+ val start: mut usize = 0+ val i: mut usize = 0+ for i <= data.len {+ if i == data.len || bytes.Bytes.at(data, i) == 10 {+ val line: bytes.Bytes = bytes.Bytes.slice(data, start, i)+ if line.len >= 64 {+ val raw: ref u8 = @alloc(32) as ref u8+ if objid.hex_decode(line.ptr, 32, raw) {+ @append(out, objid.id(raw))+ } else {+ @free(raw as ref void)+ }+ }+ start = i + 1+ }+ i+++ }+ files.free_buffer(data)+ }+ return out+}++pub fn is_native(native: list[objid.Id], id: objid.Id) bool = {+ for x in native {+ if objid.Id.eql(x, id) {+ return true+ }+ }+ return false+}--- /dev/null+++ b/veins/src/git/mirror.sx@@ -0,0 +1,158 @@+/// Prepare the `.veins/git` mirror from an existing git repository.++val str = use("std/string")+val bytes = use("../core/bytes.sx")+val layout = use("../store/layout.sx")+val files = use("../io/files.sx")++extern (C) fn c_link(oldpath: ref u8, newpath: ref u8) i32 = "link"++fn has_git_dir(path: str.StringView) bool = {+ val marker: str.StringView = files.join(path, str.from_cstr(c".git"))+ val dir: bool = files.exists_dir(marker)+ files.free_path(marker)+ return dir+}++fn is_bare(path: str.StringView) bool = {+ val head: str.StringView = files.join(path, str.from_cstr(c"HEAD"))+ val objects: str.StringView = files.join(path, str.from_cstr(c"objects"))+ val success: bool = files.exists_file(head) && files.exists_dir(objects)+ files.free_path(head)+ files.free_path(objects)+ return success+}++fn gitdir_from_file(path: str.StringView) option[str.StringView] = {+ val data_opt = files.read_all(path)+ match data_opt {+ some data => {+ val prefix: bytes.Bytes = bytes.bytes(c"gitdir: ", 8)+ if !bytes.Bytes.starts_with(data, prefix) {+ files.free_buffer(data)+ return none+ }+ val raw: bytes.Bytes = bytes.Bytes.slice(data, 8, data.len)+ val end: mut usize = raw.len+ for end > 0 && (bytes.Bytes.at(+ raw,+ end - 1+ ) == 10 || bytes.Bytes.at(raw, end - 1) == 13) {+ end--+ }+ val value: bytes.Bytes = bytes.Bytes.slice(raw, 0, end)+ val view: str.StringView = str.view(value.ptr, value.len as i64)+ val out: mut str.StringView = str.view(none, 0)+ if view.len > 0 && trust @load8(view.ptr) == 47 {+ out = files.with_suffix(view, str.view(none, 0))+ } else {+ val parent: str.StringView = files.basename(path)+ val parent_path: str.StringView = str.view(path.ptr, path.len - parent.len)+ out = files.join(parent_path, view)+ }+ files.free_buffer(data)+ return some out+ }+ none => {+ return none+ }+ }+}++/// Resolve a user-supplied path to the git directory it names.+pub fn resolve_source(source: str.StringView) option[str.StringView] = {+ if has_git_dir(source) {+ val dotgit: str.StringView = files.join(source, str.from_cstr(c".git"))+ if files.exists_dir(dotgit) {+ return some dotgit+ }+ val from_file = gitdir_from_file(dotgit)+ files.free_path(dotgit)+ return from_file+ }+ if is_bare(source) {+ return some files.with_suffix(source, str.view(none, 0))+ }+ return none+}++fn try_link(src: str.StringView, dst: str.StringView) bool = trust {+ val s: ref u8 = src.ptr+ val d: ref u8 = dst.ptr+ return c_link(s, d) == 0+}++fn copy_file_fallback(src: str.StringView, dst: str.StringView) bool = {+ val data_opt = files.read_all(src)+ match data_opt {+ some data => {+ val wrote: bool = files.write_all(dst, data)+ files.free_buffer(data)+ return wrote+ }+ none => {+ return false+ }+ }+}++fn copy_tree(src: str.StringView, dst: str.StringView) bool = trust {+ if !files.exists_dir(dst) {+ if !files.mkdir_all(dst) {+ return false+ }+ }+ val names: list[ref u8] = files.list_dir(src)+ val failed: mut bool = false+ for n in names {+ val name: str.StringView = str.from_cstr(n)+ val s: str.StringView = files.join(src, name)+ val d: str.StringView = files.join(dst, name)+ if files.exists_dir(s) {+ if !copy_tree(s, d) {+ failed = true+ }+ } elif files.exists_file(s) {+ if !try_link(s, d) {+ if !copy_file_fallback(s, d) {+ failed = true+ }+ }+ }+ files.free_path(s)+ files.free_path(d)+ }+ files.free_names(names)+ return !failed+}++/// Copy the source git directory into `.veins/git`. Existing mirrors are left+/// untouched and treated as already prepared.+pub fn prepare(repo: layout.Repo, source: str.StringView) i32 = trust {+ val target: str.StringView = layout.git_dir(repo)+ val head: str.StringView = files.join(target, str.from_cstr(c"HEAD"))+ val already: bool = files.exists_file(head)+ files.free_path(head)+ if already {+ files.free_path(target)+ return 0+ }+ val src_opt = resolve_source(source)+ val src: mut str.StringView = str.view(none, 0)+ match src_opt {+ some s => {+ src = s+ }+ none => {+ files.free_path(target)+ return 2+ }+ }+ val success: bool = copy_tree(src, target)+ files.free_path(src)+ files.free_path(target)+ if success {+ return 0+ }+ return 3+}--- /dev/null+++ b/veins/src/git/object.sx@@ -0,0 +1,1241 @@+/// Read-only access to a git object database.+///+/// Supports loose objects, pack v2/v3 files with OFS/REF deltas, and both v1+/// and v2 pack indexes. The importer uses this instead of shelling out to git.++lib "z"+lib "crypto"++val str = use("std/string")+val bytes = use("../core/bytes.sx")+val buf = use("../core/buf.sx")+val lists = use("../core/lists.sx")+val files = use("../io/files.sx")++pub enum GitError = {+ NotFound+ Corrupt+ Unsupported+ Io+ HashMismatch+ OutOfMemory+}++pub fn error_name(e: GitError) str.StringView = {+ match e {+ GitError.NotFound => {+ return "object not found"+ }+ GitError.Corrupt => {+ return "corrupt git object data"+ }+ GitError.Unsupported => {+ return "unsupported git format"+ }+ GitError.Io => {+ return "git object I/O error"+ }+ GitError.HashMismatch => {+ return "git object hash mismatch"+ }+ GitError.OutOfMemory => {+ return "out of memory"+ }+ }+ return "git error"+}++pub val KIND_COMMIT: u8 = 1+pub val KIND_TREE: u8 = 2+pub val KIND_BLOB: u8 = 3+pub val KIND_TAG: u8 = 4+pub val KIND_OFS_DELTA: u8 = 6+pub val KIND_REF_DELTA: u8 = 7++pub type Object = {+ kind: u8+ body: bytes.Bytes+ alloc: bytes.Bytes+}++pub fn free_object(o: Object) void = trust {+ if o.alloc.ptr != none {+ val p: mut ref void = o.alloc.ptr as ref void+ @free(p)+ }+}++type GitCacheEntry = {+ offset: mut u64+ kind: mut u8+ body: mut bytes.Bytes+}++type GitPack = {+ path: mut str.StringView+ data: mut bytes.Bytes+ count: mut usize+ oids: mut ref u8+ offsets: mut ref u8+ cache: mut list[ref GitCacheEntry]+ cache_map: mut ref u32+ cache_map_cap: mut usize+ cache_bytes: mut usize+ cache_count: mut usize+}++val CACHE_MIN: usize = 0+val CACHE_MAX_BYTES: usize = 536870912+val CACHE_MAX_ENTRIES: usize = 32768+val CACHE_MAP_CAP: usize = 262144++pub type GitRepo = {+ git_dir: mut str.StringView+ packs: list[ref GitPack]+}++extern (C) fn uncompress(+ dest: ref u8,+ dest_len: ref u64,+ source: ref u8,+ source_len: u64+) i32 = "uncompress"+++fn be32_at(data: bytes.Bytes, off: usize) u32 = trust {+ val p: ref u8 = @ptradd(data.ptr, off as i64)+ return ((@load8(p) as u32) << 24) | ((@load8(@ptradd(p, 1)) as u32) << 16)+ | ((@load8(@ptradd(p, 2)) as u32) << 8) | (@load8(@ptradd(p, 3)) as u32)+}++fn be64_at(data: bytes.Bytes, off: usize) u64 = trust {+ val p: ref u8 = @ptradd(data.ptr, off as i64)+ val hi: u64 = ((@load8(p) as u64) << 56) | ((@load8(@ptradd(p, 1)) as u64) << 48)+ | ((@load8(@ptradd(p, 2)) as u64) << 40) | ((@load8(@ptradd(p, 3)) as u64) << 32)+ val lo: u64 = ((@load8(@ptradd(p, 4)) as u64) << 24) | ((@load8(@ptradd(p, 5)) as u64) << 16)+ | ((@load8(@ptradd(p, 6)) as u64) << 8) | (@load8(@ptradd(p, 7)) as u64)+ return hi | lo+}++extern (C) fn SHA1(data: ref u8, len: usize, out: ref u8) ref u8 = "SHA1"++fn sha1_of(data: bytes.Bytes) option[bytes.Bytes] = trust {+ val out: ref u8 = @alloc(20) as ref u8+ val r: ref u8 = SHA1(data.ptr, data.len, out)+ if r == none {+ @free(out as ref void)+ return none+ }+ return some bytes.bytes(out, 20)+}++pub fn free_digest(d: bytes.Bytes) void = trust {+ if d.ptr != none {+ val p: mut ref void = d.ptr as ref void+ @free(p)+ }+}++fn put_decimal(b: mut buf.Buf, v: u64) void = trust {+ if v == 0 {+ buf.Buf.put_u8(b, 48)+ return+ }+ val tmp: ref u8 = @alloc(24) as ref u8+ val n: mut usize = 0+ val x: mut u64 = v+ for x > 0 {+ @store8(@ptradd(tmp, n as i64), (48 + (x % 10)) as u8)+ x = x / 10+ n+++ }+ val i: mut usize = n+ for i > 0 {+ i--+ buf.Buf.put_u8(b, @load8(@ptradd(tmp, i as i64)))+ }+ @free(tmp as ref void)+}++fn kind_name(kind: u8) str.StringView = {+ if kind == KIND_COMMIT {+ return "commit"+ }+ if kind == KIND_TREE {+ return "tree"+ }+ if kind == KIND_BLOB {+ return "blob"+ }+ if kind == KIND_TAG {+ return "tag"+ }+ return "unknown"+}++fn kind_from_name(name: bytes.Bytes) u8 = {+ if bytes.Bytes.eql(name, bytes.bytes(c"commit", 6)) {+ return KIND_COMMIT+ }+ if bytes.Bytes.eql(name, bytes.bytes(c"tree", 4)) {+ return KIND_TREE+ }+ if bytes.Bytes.eql(name, bytes.bytes(c"blob", 4)) {+ return KIND_BLOB+ }+ if bytes.Bytes.eql(name, bytes.bytes(c"tag", 3)) {+ return KIND_TAG+ }+ return 0+}++/// Git object hash: SHA-1("<kind> <length>\0" || body).+pub fn object_hash(kind: u8, body: bytes.Bytes) option[bytes.Bytes] = trust {+ val b: mut buf.Buf = buf.new(body.len + 32)+ buf.Buf.put_bytes(b, bytes.from_cstr(kind_name(kind).ptr))+ buf.Buf.put_u8(b, 32)+ put_decimal(b, body.len as u64)+ buf.Buf.put_u8(b, 0)+ buf.Buf.put_bytes(b, body)+ val out = sha1_of(buf.Buf.view(b))+ buf.Buf.free(b)+ return out+}++fn verify_hash(oid: bytes.Bytes, kind: u8, body: bytes.Bytes) bool = trust {+ val got = object_hash(kind, body)+ match got {+ some h => {+ val same: bool = bytes.Bytes.eql(h, oid)+ free_digest(h)+ return same+ }+ none => {+ return false+ }+ }+}++fn inflate_exact(input: bytes.Bytes, expected: usize) option[bytes.Bytes] = trust {+ val cap: usize = expected + 1+ val dst: ref u8 = @alloc(cap) as ref u8+ val dest_len: ref u64 = @alloc(8) as ref u64+ @store64(dest_len as ref void, expected as u64)+ val rc: i32 = uncompress(+ dst,+ dest_len,+ input.ptr,+ input.len as u64+ )+ val got: u64 = @load64(dest_len as ref void) as u64+ @free(dest_len as ref void)+ if rc != 0 || got != expected as u64 {+ @free(dst as ref void)+ return none+ }+ return some bytes.bytes(dst, expected)+}++fn inflate_unknown(input: bytes.Bytes) option[bytes.Bytes] = trust {+ val base: mut usize = input.len * 3 + 4096+ for base <= 1073741824 {+ val dst: ref u8 = @alloc(base + 1) as ref u8+ val dest_len: ref u64 = @alloc(8) as ref u64+ @store64(dest_len as ref void, base as u64)+ val rc: i32 = uncompress(dst, dest_len, input.ptr, input.len as u64)+ val got: u64 = @load64(dest_len as ref void) as u64+ @free(dest_len as ref void)+ if rc == 0 {+ return some bytes.bytes(dst, got as usize)+ }+ @free(dst as ref void)+ if rc != -5 {+ return none+ }+ base = base * 2+ }+ return none+}++fn hex_digit(n: u8) u8 = {+ if n < 10 {+ return (48 + n) as u8+ }+ return (87 + n) as u8+}++fn oid_hex(oid: bytes.Bytes) ref u8 = trust {+ val out: ref u8 = @alloc(41) as ref u8+ val i: mut usize = 0+ for i < 20 {+ val v: u8 = bytes.Bytes.at(oid, i)+ @store8(@ptradd(out, (i * 2) as i64), hex_digit(v >> 4))+ @store8(@ptradd(out, (i * 2 + 1) as i64), hex_digit(v & 15))+ i+++ }+ @store8(@ptradd(out, 40), 0)+ return out+}++type GitVarint = {+ value: u64+ next: usize+}++fn read_be_varint(data: bytes.Bytes, start: usize) option[GitVarint] = {+ if start >= data.len {+ return none+ }+ val c0: u8 = bytes.Bytes.at(data, start)+ val size: mut u64 = (c0 & 0x0f) as u64+ val shift: mut u64 = 4+ val i: mut usize = start + 1+ val more: mut bool = (c0 & 0x80) != 0+ for more {+ if i >= data.len {+ return none+ }+ val c: u8 = bytes.Bytes.at(data, i)+ i+++ size = size | (((c & 0x7f) as u64) << shift)+ shift = shift + 7+ more = (c & 0x80) != 0+ }+ return some GitVarint{value: size, next: i}+}++fn read_delta_varint(data: bytes.Bytes, start: usize) option[GitVarint] = {+ val v: mut u64 = 0+ val shift: mut u64 = 0+ val i: mut usize = start+ for {+ if i >= data.len || shift > 63 {+ return none+ }+ val c: u8 = bytes.Bytes.at(data, i)+ i+++ v = v | (((c & 0x7f) as u64) << shift)+ shift = shift + 7+ if (c & 0x80) == 0 {+ return some GitVarint{value: v, next: i}+ }+ }+ return none+}++fn apply_delta(base: bytes.Bytes, delta: bytes.Bytes) option[bytes.Bytes] = trust {+ val src_opt = read_delta_varint(delta, 0)+ val src_size: mut u64 = 0+ val p: mut usize = 0+ match src_opt {+ some r => {+ src_size = r.value+ p = r.next+ }+ none => {+ return none+ }+ }+ if src_size != base.len as u64 {+ return none+ }+ val dst_opt = read_delta_varint(delta, p)+ val dst_size: mut u64 = 0+ match dst_opt {+ some r => {+ dst_size = r.value+ p = r.next+ }+ none => {+ return none+ }+ }+ if dst_size > 2147483648 {+ return none+ }+ val cap: usize = dst_size as usize+ val out: ref u8 = @alloc(cap + 1) as ref u8+ val written: mut usize = 0+ for p < delta.len {+ val op: u8 = bytes.Bytes.at(delta, p)+ p+++ if (op & 0x80) != 0 {+ val off: mut u64 = 0+ val size: mut u64 = 0+ if (op & 0x01) != 0 {+ if p >= delta.len {+ @free(out as ref void)+ return none+ }+ off = off | (bytes.Bytes.at(delta, p) as u64)+ p+++ }+ if (op & 0x02) != 0 {+ if p >= delta.len {+ @free(out as ref void)+ return none+ }+ off = off | ((bytes.Bytes.at(delta, p) as u64) << 8)+ p+++ }+ if (op & 0x04) != 0 {+ if p >= delta.len {+ @free(out as ref void)+ return none+ }+ off = off | ((bytes.Bytes.at(delta, p) as u64) << 16)+ p+++ }+ if (op & 0x08) != 0 {+ if p >= delta.len {+ @free(out as ref void)+ return none+ }+ off = off | ((bytes.Bytes.at(delta, p) as u64) << 24)+ p+++ }+ if (op & 0x10) != 0 {+ if p >= delta.len {+ @free(out as ref void)+ return none+ }+ size = size | (bytes.Bytes.at(delta, p) as u64)+ p+++ }+ if (op & 0x20) != 0 {+ if p >= delta.len {+ @free(out as ref void)+ return none+ }+ size = size | ((bytes.Bytes.at(delta, p) as u64) << 8)+ p+++ }+ if (op & 0x40) != 0 {+ if p >= delta.len {+ @free(out as ref void)+ return none+ }+ size = size | ((bytes.Bytes.at(delta, p) as u64) << 16)+ p+++ }+ if size == 0 {+ size = 65536+ }+ if off > base.len as u64 || size > (base.len as u64) - off {+ @free(out as ref void)+ return none+ }+ if size > (cap as u64) - (written as u64) {+ @free(out as ref void)+ return none+ }+ if size > 0 {+ @memcpy(+ @ptradd(out, written as i64) as ref void,+ @ptradd(base.ptr, off as i64) as ref void,+ size as usize+ )+ }+ written = written + size as usize+ } else {+ if op == 0 {+ @free(out as ref void)+ return none+ }+ val n: usize = op as usize+ if p + n > delta.len || n > cap - written {+ @free(out as ref void)+ return none+ }+ @memcpy(+ @ptradd(out, written as i64) as ref void,+ @ptradd(delta.ptr, p as i64) as ref void,+ n+ )+ p = p + n+ written = written + n+ }+ }+ if written != cap {+ @free(out as ref void)+ return none+ }+ return some bytes.bytes(out, cap)+}++fn find_oid(pack: ref GitPack, oid: bytes.Bytes) option[usize] = trust {+ pre {+ oid_len: oid.len == 20+ }+ val lo: mut usize = 0+ val hi: mut usize = pack.count+ for lo < hi {+ val mid: usize = lo + (hi - lo) / 2+ val cur: bytes.Bytes = bytes.bytes(@ptradd(pack.oids, (mid * 20) as i64), 20)+ val c: i64 = bytes.Bytes.cmp(cur, oid)+ if c == 0 {+ return some mid+ }+ if c < 0 {+ lo = mid + 1+ } else {+ hi = mid+ }+ }+ return none+}++fn offset_at(pack: ref GitPack, i: usize) u64 = trust {+ return @load64(@ptradd(pack.offsets, (i * 8) as i64)) as u64+}++fn cache_hash(offset: u64) usize = {+ val h: u64 = offset * 11400714819323198485+ return (h >> 32) as usize+}++fn cache_slot(pack: ref GitPack, offset: u64) i64 = trust {+ if pack.cache_map_cap == 0 {+ return -1+ }+ val mask: usize = pack.cache_map_cap - 1+ val start: usize = cache_hash(offset) & mask+ val idx: mut usize = start+ for {+ val slot: ref u32 = @ptradd(pack.cache_map as ref void, (idx * 4) as i64) as ref u32+ val v: u32 = @load32(slot) as u32+ if v == 0 {+ return -1+ }+ if v != 4294967295 {+ val ei: usize = (v - 1) as usize+ val o = @get(pack.cache, ei)+ if o is some e {+ if e.body.ptr != none && e.offset == offset {+ return ei as i64+ }+ }+ }+ idx = (idx + 1) & mask+ if idx == start {+ return -1+ }+ }+ return -1+}++fn cache_map_put(pack: ref GitPack, offset: u64, entry: usize) void = trust {+ if pack.cache_map_cap == 0 {+ return+ }+ val mask: usize = pack.cache_map_cap - 1+ val start: usize = cache_hash(offset) & mask+ val idx: mut usize = start+ val tomb: mut i64 = -1+ for {+ val slot: ref u32 = @ptradd(pack.cache_map as ref void, (idx * 4) as i64) as ref u32+ val v: u32 = @load32(slot) as u32+ if v == 0 {+ val at: mut usize = idx+ if tomb >= 0 {+ at = tomb as usize+ }+ val at_slot: ref u32 = @ptradd(pack.cache_map as ref void, (at * 4) as i64) as ref u32+ @store32(at_slot as ref void, (entry + 1) as i32)+ return+ }+ if v == 4294967295 && tomb < 0 {+ tomb = idx as i64+ }+ idx = (idx + 1) & mask+ if idx == start {+ if tomb >= 0 {+ val tslot: ref u32 = @ptradd(+ pack.cache_map as ref void,+ ((tomb as usize) * 4) as i64+ ) as ref u32+ @store32(tslot as ref void, (entry + 1) as i32)+ }+ return+ }+ }+}++fn cache_map_remove(pack: ref GitPack, offset: u64) void = trust {+ if pack.cache_map_cap == 0 {+ return+ }+ val mask: usize = pack.cache_map_cap - 1+ val start: usize = cache_hash(offset) & mask+ val idx: mut usize = start+ for {+ val slot: ref u32 = @ptradd(pack.cache_map as ref void, (idx * 4) as i64) as ref u32+ val v: u32 = @load32(slot) as u32+ if v == 0 {+ return+ }+ if v != 4294967295 {+ val ei: usize = (v - 1) as usize+ val o = @get(pack.cache, ei)+ if o is some e {+ if e.offset == offset {+ @store32(slot as ref void, -1)+ return+ }+ }+ }+ idx = (idx + 1) & mask+ if idx == start {+ return+ }+ }+}++fn cache_lookup(pack: ref GitPack, offset: u64) option[Object] = trust {+ val slot: i64 = cache_slot(pack, offset)+ if slot < 0 {+ return none+ }+ val o = @get(pack.cache, slot as usize)+ if o is some e {+ return some Object{kind: e.kind, body: e.body, alloc: bytes.empty()}+ }+ return none+}++fn cache_evict_one(pack: mut ref GitPack) void = trust {+ val victim: mut i64 = -1+ val oldest_off: mut u64 = 18446744073709551615+ val i: mut usize = 0+ for i < @len(pack.cache) {+ val o = @get(pack.cache, i)+ if o is some e {+ if e.body.ptr != none && e.offset < oldest_off {+ oldest_off = e.offset+ victim = i as i64+ }+ }+ i+++ }+ if victim < 0 {+ return+ }+ val vo = @get(pack.cache, victim as usize)+ if vo is some e2 {+ if e2.body.ptr != none {+ pack.cache_bytes = pack.cache_bytes - e2.body.len+ pack.cache_count = pack.cache_count - 1+ cache_map_remove(pack, e2.offset)+ val bp: mut ref void = e2.body.ptr as ref void+ @free(bp)+ e2.body = bytes.empty()+ }+ }+}++fn cache_store(pack: mut ref GitPack, offset: u64, kind: u8, body: bytes.Bytes) bool = trust {+ if body.len < CACHE_MIN || body.len > CACHE_MAX_BYTES {+ return false+ }+ if cache_slot(pack, offset) >= 0 {+ return false+ }+ for pack.cache_count > 0 {+ if pack.cache_bytes + body.len <= CACHE_MAX_BYTES+ && pack.cache_count < CACHE_MAX_ENTRIES {+ break+ }+ cache_evict_one(pack)+ }+ if pack.cache_bytes + body.len > CACHE_MAX_BYTES {+ return false+ }+ val e: mut ref GitCacheEntry = @alloc(@sizeof(GitCacheEntry)) as ref GitCacheEntry+ e.offset = offset+ e.kind = kind+ e.body = body+ val slot: mut i64 = -1+ val i: mut usize = 0+ for i < @len(pack.cache) {+ val o = @get(pack.cache, i)+ if o is some x {+ if x.body.ptr == none {+ slot = i as i64+ break+ }+ }+ i+++ }+ if slot >= 0 {+ @set(pack.cache, slot as usize, e)+ } else {+ @append(pack.cache, e)+ }+ pack.cache_bytes = pack.cache_bytes + body.len+ pack.cache_count = pack.cache_count + 1+ val map_slot: usize = @len(pack.cache) - 1+ if slot >= 0 {+ cache_map_put(pack, offset, slot as usize)+ } else {+ cache_map_put(pack, offset, map_slot)+ }+ return true+}++fn cache_free(pack: ref GitPack) void = trust {+ if pack.cache_map != none {+ @free(pack.cache_map as ref void)+ }+ for e in pack.cache {+ if e.body.ptr != none {+ val bp: mut ref void = e.body.ptr as ref void+ @free(bp)+ }+ val ep: mut ref void = e as ref void+ @free(ep)+ }+ @listfree(pack.cache)+}++fn read_at(+ repo: GitRepo,+ pack: mut ref GitPack,+ start: u64,+ verify: bool,+ use_cache: bool+) result[Object, GitError] = trust {+ if use_cache {+ val cached = cache_lookup(pack, start)+ if cached is some c {+ return ok c+ }+ }+ val data: bytes.Bytes = pack.data+ val pos: mut usize = start as usize+ if pos >= data.len {+ return err GitError.Corrupt+ }+ val c0: u8 = bytes.Bytes.at(data, pos)+ val kind: u8 = (c0 >> 4) & 7+ val size_opt = read_be_varint(data, start as usize)+ val size: mut u64 = 0+ match size_opt {+ some v => {+ size = v.value+ pos = v.next+ }+ none => {+ return err GitError.Corrupt+ }+ }+ if size > 2147483648 {+ return err GitError.Unsupported+ }++ val base_oid: mut bytes.Bytes = bytes.empty()+ val base_off: mut u64 = 0+ val has_base_off: mut bool = false+ if kind == KIND_OFS_DELTA {+ if pos >= data.len {+ return err GitError.Corrupt+ }+ val c: u8 = bytes.Bytes.at(data, pos)+ pos+++ val acc: mut u64 = (c & 0x7f) as u64+ val more: mut bool = (c & 0x80) != 0+ for more {+ if pos >= data.len {+ return err GitError.Corrupt+ }+ val c2: u8 = bytes.Bytes.at(data, pos)+ pos+++ acc = ((acc + 1) << 7) | ((c2 & 0x7f) as u64)+ more = (c2 & 0x80) != 0+ }+ has_base_off = true+ base_off = start - acc+ } elif kind == KIND_REF_DELTA {+ if pos + 20 > data.len {+ return err GitError.Corrupt+ }+ base_oid = bytes.Bytes.slice(data, pos, pos + 20)+ pos = pos + 20+ }++ val comp: bytes.Bytes = bytes.Bytes.slice(data, pos, data.len)+ val inflated_opt = inflate_exact(comp, size as usize)+ val inflated: mut bytes.Bytes = bytes.empty()+ match inflated_opt {+ some x => {+ inflated = x+ }+ none => {+ return err GitError.Corrupt+ }+ }++ if kind >= KIND_COMMIT && kind <= KIND_TAG {+ if use_cache && cache_store(pack, start, kind, inflated) {+ return ok Object{kind: kind, body: inflated, alloc: bytes.empty()}+ }+ return ok Object{kind: kind, body: inflated, alloc: inflated}+ }+ if kind != KIND_OFS_DELTA && kind != KIND_REF_DELTA {+ @free(inflated.ptr as ref void)+ return err GitError.Corrupt+ }++ val base: mut Object = Object{kind: 0, body: bytes.empty(), alloc: bytes.empty()}+ if has_base_off {+ if base_off >= start {+ @free(inflated.ptr as ref void)+ return err GitError.Corrupt+ }+ val br = read_at(repo, pack, base_off, verify, use_cache)+ match br {+ ok b => {+ base = b+ }+ err e => {+ @free(inflated.ptr as ref void)+ return err e+ }+ }+ } else {+ val br2 = read_impl(repo, base_oid, verify, use_cache)+ match br2 {+ ok b => {+ base = b+ }+ err e => {+ @free(inflated.ptr as ref void)+ return err e+ }+ }+ }++ val merged_opt = apply_delta(base.body, inflated)+ val merged: mut bytes.Bytes = bytes.empty()+ match merged_opt {+ some x => {+ merged = x+ }+ none => {+ free_object(base)+ @free(inflated.ptr as ref void)+ return err GitError.Corrupt+ }+ }+ val base_kind: u8 = base.kind+ free_object(base)+ @free(inflated.ptr as ref void)+ if use_cache && cache_store(pack, start, base_kind, merged) {+ return ok Object{kind: base_kind, body: merged, alloc: bytes.empty()}+ }+ return ok Object{kind: base_kind, body: merged, alloc: merged}+}++fn read_loose(repo: GitRepo, oid: bytes.Bytes, verify: bool) option[Object] = trust {+ val hex: ref u8 = oid_hex(oid)+ val objroot: str.StringView = files.join(repo.git_dir, str.from_cstr(c"objects"))+ val dirname: str.StringView = str.view(hex, 2)+ val rest: str.StringView = str.view(@ptradd(hex, 2), 38)+ val dir: str.StringView = files.join(objroot, dirname)+ val path: str.StringView = files.join(dir, rest)+ files.free_path(objroot)+ files.free_path(dir)+ @free(hex as ref void)+ val exists: bool = files.exists_file(path)+ if !exists {+ files.free_path(path)+ return none+ }+ val data_opt = files.read_all(path)+ files.free_path(path)+ val compressed: mut bytes.Bytes = bytes.empty()+ match data_opt {+ some d => {+ compressed = d+ }+ none => {+ return none+ }+ }+ val inflated_opt = inflate_unknown(compressed)+ files.free_buffer(compressed)+ val inflated: mut bytes.Bytes = bytes.empty()+ match inflated_opt {+ some x => {+ inflated = x+ }+ none => {+ return none+ }+ }+ val space: mut usize = 0+ for space < inflated.len && bytes.Bytes.at(inflated, space) != 32 {+ space+++ }+ val nul: mut usize = space+ for nul < inflated.len && bytes.Bytes.at(inflated, nul) != 0 {+ nul+++ }+ if space == 0 || nul >= inflated.len {+ @free(inflated.ptr as ref void)+ return none+ }+ val kind: u8 = kind_from_name(bytes.Bytes.slice(inflated, 0, space))+ if kind == 0 {+ @free(inflated.ptr as ref void)+ return none+ }+ val size_text: bytes.Bytes = bytes.Bytes.slice(inflated, space + 1, nul)+ val declared: mut u64 = 0+ val i: mut usize = 0+ for i < size_text.len {+ val c: u8 = bytes.Bytes.at(size_text, i)+ if c < 48 || c > 57 {+ @free(inflated.ptr as ref void)+ return none+ }+ declared = declared * 10 + (c - 48) as u64+ i+++ }+ val body: bytes.Bytes = bytes.Bytes.slice(inflated, nul + 1, inflated.len)+ if body.len as u64 != declared {+ @free(inflated.ptr as ref void)+ return none+ }+ val o = Object{kind: kind, body: body, alloc: inflated}+ if verify && !verify_hash(oid, kind, body) {+ free_object(o)+ return none+ }+ return some o+}++fn read_impl(+ repo: GitRepo,+ oid: bytes.Bytes,+ verify: bool,+ use_cache: bool+) result[Object, GitError] = trust {+ pre {+ oid_len: oid.len == 20+ }+ val i: mut usize = 0+ for i < @len(repo.packs) {+ val p: mut ref GitPack = pack_at(repo.packs, i)+ val found = find_oid(p, oid)+ if found is some idx {+ val r = read_at(repo, p, offset_at(p, idx), verify, use_cache)+ match r {+ ok o => {+ if verify && !verify_hash(oid, o.kind, o.body) {+ free_object(o)+ return err GitError.HashMismatch+ }+ return ok o+ }+ err e => {+ return err e+ }+ }+ }+ i+++ }+ val loose = read_loose(repo, oid, verify)+ if loose is some o2 {+ return ok o2+ }+ return err GitError.NotFound+}++pub fn read(repo: GitRepo, oid: bytes.Bytes) result[Object, GitError] = trust {+ return read_impl(repo, oid, true, false)+}++/// Read an object without recomputing its hash. The pack trailer and index are+/// already verified when the pack is opened, so this is safe for local import.+pub fn read_fast(repo: GitRepo, oid: bytes.Bytes) result[Object, GitError] = trust {+ return read_impl(repo, oid, false, true)+}++fn pack_at(packs: list[ref GitPack], i: usize) ref GitPack = {+ val o = @get(packs, i)+ if o is some p {+ return p+ }+ assert false+ return none+}++fn parse_idx(+ data: bytes.Bytes,+ pack_count: usize,+ pack_trailer: bytes.Bytes+) result[ref GitPack, GitError] = trust {+ if data.len < 40 {+ return err GitError.Corrupt+ }+ val trailer_off: usize = data.len - 20+ val check_opt = sha1_of(bytes.Bytes.slice(data, 0, trailer_off))+ val check: mut bytes.Bytes = bytes.empty()+ match check_opt {+ some d => {+ check = d+ }+ none => {+ return err GitError.OutOfMemory+ }+ }+ val check_ok: bool = bytes.Bytes.eql(check, bytes.Bytes.slice(data, trailer_off, data.len))+ free_digest(check)+ if !check_ok {+ return err GitError.Corrupt+ }+ if !bytes.Bytes.eql(+ bytes.Bytes.slice(data, data.len - 40, data.len - 20),+ pack_trailer+ ) {+ return err GitError.Corrupt+ }++ val is_v2: bool = data.len >= 8+ && bytes.Bytes.at(data, 0) == 255+ && bytes.Bytes.at(data, 1) == 116+ && bytes.Bytes.at(data, 2) == 79+ && bytes.Bytes.at(data, 3) == 99+ val fanout_off: mut usize = 0+ if is_v2 {+ fanout_off = 8+ }+ if is_v2 {+ val version: u32 = be32_at(data, 4)+ if version != 2 {+ return err GitError.Unsupported+ }+ }+ if data.len < fanout_off + 1024 + 40 {+ return err GitError.Corrupt+ }+ val n: usize = be32_at(data, fanout_off + 255 * 4) as usize+ if n != pack_count {+ return err GitError.Corrupt+ }+ val oids: ref u8 = @alloc(n * 20 + 1) as ref u8+ val offsets: ref u8 = @alloc(n * 8 + 1) as ref u8+ if is_v2 {+ val names_off: usize = fanout_off + 1024+ val crcs_off: usize = names_off + n * 20+ val offs_off: usize = crcs_off + n * 4+ val large_off: usize = offs_off + n * 4+ if large_off + 40 > data.len {+ @free(oids as ref void)+ @free(offsets as ref void)+ return err GitError.Corrupt+ }+ val large_bytes: usize = data.len - 40 - large_off+ if large_bytes % 8 != 0 {+ @free(oids as ref void)+ @free(offsets as ref void)+ return err GitError.Corrupt+ }+ val i: mut usize = 0+ for i < n {+ @memcpy(+ @ptradd(oids, (i * 20) as i64) as ref void,+ @ptradd(data.ptr, (names_off + i * 20) as i64) as ref void,+ 20+ )+ val raw_off: u32 = be32_at(data, offs_off + i * 4)+ val resolved: mut u64 = raw_off as u64+ if (raw_off & 2147483648) != 0 {+ val idx: usize = (raw_off & 2147483647) as usize+ if idx * 8 + 8 > large_bytes {+ @free(oids as ref void)+ @free(offsets as ref void)+ return err GitError.Corrupt+ }+ resolved = be64_at(data, large_off + idx * 8)+ }+ @store64(@ptradd(offsets, (i * 8) as i64), resolved as i64)+ i+++ }+ } else {+ val records_off: usize = 1024+ if records_off + n * 24 + 40 > data.len {+ @free(oids as ref void)+ @free(offsets as ref void)+ return err GitError.Corrupt+ }+ val j: mut usize = 0+ for j < n {+ val rec: usize = records_off + j * 24+ val off: u64 = be32_at(data, rec) as u64+ @store64(@ptradd(offsets, (j * 8) as i64), off as i64)+ @memcpy(+ @ptradd(oids, (j * 20) as i64) as ref void,+ @ptradd(data.ptr, (rec + 4) as i64) as ref void,+ 20+ )+ j+++ }+ }++ val p: mut ref GitPack = @alloc(@sizeof(GitPack)) as ref GitPack+ p.path = str.view(none, 0)+ p.data = bytes.empty()+ p.count = n+ p.oids = oids+ p.offsets = offsets+ p.cache = lists.new[ref GitCacheEntry]()+ p.cache_map_cap = CACHE_MAP_CAP+ p.cache_map = @alloc(CACHE_MAP_CAP * 4) as ref u32+ @memset(p.cache_map as ref void, 0, CACHE_MAP_CAP * 4)+ p.cache_bytes = 0+ p.cache_count = 0+ return ok p+}++fn open_pack(+ pack_path: str.StringView,+ idx_path: str.StringView+) result[ref GitPack, GitError] = trust {+ val pdata_opt = files.read_all(pack_path)+ val pdata: mut bytes.Bytes = bytes.empty()+ match pdata_opt {+ some d => {+ pdata = d+ }+ none => {+ return err GitError.Io+ }+ }+ if pdata.len < 32 || !bytes.Bytes.eql(bytes.Bytes.slice(pdata, 0, 4), bytes.bytes(c"PACK", 4)) {+ files.free_buffer(pdata)+ return err GitError.Corrupt+ }+ val version: u32 = be32_at(pdata, 4)+ if version != 2 && version != 3 {+ files.free_buffer(pdata)+ return err GitError.Unsupported+ }+ val count: usize = be32_at(pdata, 8) as usize+ val trailer_off: usize = pdata.len - 20+ val pack_trailer: bytes.Bytes = bytes.Bytes.slice(pdata, trailer_off, pdata.len)+ val hash_opt = sha1_of(bytes.Bytes.slice(pdata, 0, trailer_off))+ val hash: mut bytes.Bytes = bytes.empty()+ match hash_opt {+ some d => {+ hash = d+ }+ none => {+ files.free_buffer(pdata)+ return err GitError.OutOfMemory+ }+ }+ val hash_ok: bool = bytes.Bytes.eql(hash, pack_trailer)+ free_digest(hash)+ if !hash_ok {+ files.free_buffer(pdata)+ return err GitError.Corrupt+ }++ val idata_opt = files.read_all(idx_path)+ val idata: mut bytes.Bytes = bytes.empty()+ match idata_opt {+ some d => {+ idata = d+ }+ none => {+ files.free_buffer(pdata)+ return err GitError.Io+ }+ }+ val pr = parse_idx(idata, count, pack_trailer)+ files.free_buffer(idata)+ val p: mut ref GitPack = none+ match pr {+ ok x => {+ p = x+ }+ err e => {+ files.free_buffer(pdata)+ return err e+ }+ }+ p.path = pack_path+ p.data = pdata+ return ok p+}++pub fn open(git_dir: str.StringView) result[GitRepo, GitError] = trust {+ val packs: mut list[ref GitPack] = lists.new[ref GitPack]()+ val pack_dir: str.StringView = files.join(git_dir, str.from_cstr(c"objects/pack"))+ if files.exists_dir(pack_dir) {+ val names: list[ref u8] = files.list_dir(pack_dir)+ for n in names {+ if files.name_ends_with(n, c".idx") {+ val iv: str.StringView = str.from_cstr(n)+ val base: str.StringView = str.view(iv.ptr, iv.len - 4)+ val pack_name: str.StringView = files.with_suffix(base, ".pack")+ val pack_path: str.StringView = files.join(pack_dir, pack_name)+ val idx_path: str.StringView = files.join(pack_dir, iv)+ files.free_path(pack_name)+ if files.exists_file(pack_path) {+ val r = open_pack(pack_path, idx_path)+ match r {+ ok p => {+ @append(packs, p)+ files.free_path(idx_path)+ }+ err e => {+ files.free_path(pack_path)+ files.free_path(idx_path)+ files.free_names(names)+ files.free_path(pack_dir)+ for x in packs {+ free_pack(x)+ }+ @listfree(packs)+ return err e+ }+ }+ } else {+ files.free_path(pack_path)+ files.free_path(idx_path)+ }+ }+ }+ files.free_names(names)+ }+ files.free_path(pack_dir)+ return ok GitRepo{git_dir: git_dir, packs: packs}+}++pub fn free_pack(p: ref GitPack) void = trust {+ files.free_buffer(p.data)+ cache_free(p)+ if p.oids != none {+ @free(p.oids as ref void)+ }+ if p.offsets != none {+ @free(p.offsets as ref void)+ }+ if p.path.ptr != none {+ files.free_path(p.path)+ }+ @free(p as ref void)+}++pub fn free(repo: mut GitRepo) void = trust {+ for p in repo.packs {+ free_pack(p)+ }+ @listfree(repo.packs)+ if repo.git_dir.ptr != none {+ files.free_path(repo.git_dir)+ }+ repo.git_dir = str.view(none, 0)+}--- /dev/null+++ b/veins/src/git/oidmap.sx@@ -0,0 +1,198 @@+/// A small open-addressed map keyed by 20-byte git object IDs.+///+/// Slots store the key, a 32-byte payload, and a used flag. This is used for+/// reachability sets and for the in-memory git-to-veins ID maps during import.++val bytes = use("../core/bytes.sx")++pub val OID_LEN: usize = 20+pub val VALUE_LEN: usize = 32+pub val SLOT_LEN: usize = 56++pub type OidMap = {+ slots: mut ref u8+ cap: mut usize+ len: mut usize+}++fn round_cap(n: usize) usize = trust {+ val c: mut usize = 16+ for c < n {+ c = c * 2+ }+ return c+}++fn oid_ptr(map: OidMap, i: usize) ref u8 = trust {+ return @ptradd(map.slots, (i * SLOT_LEN + 1) as i64)+}++fn value_ptr(map: OidMap, i: usize) ref u8 = trust {+ return @ptradd(map.slots, (i * SLOT_LEN + 1 + OID_LEN) as i64)+}++fn used_at(map: OidMap, i: usize) bool = trust {+ return @load8(@ptradd(map.slots, (i * SLOT_LEN) as i64)) != 0+}++fn set_used(map: OidMap, i: usize) void = trust {+ @store8(@ptradd(map.slots, (i * SLOT_LEN) as i64), 1)+}++fn hash_oid(oid: bytes.Bytes) u64 = trust {+ val h: mut u64 = 1469598103934665603+ val k: mut usize = 0+ for k < OID_LEN {+ h = (h ^ (bytes.Bytes.at(oid, k) as u64)) * 1099511628211+ k+++ }+ return h+}++fn slot_eql(map: OidMap, i: usize, oid: bytes.Bytes) bool = trust {+ return bytes.Bytes.eql(bytes.bytes(oid_ptr(map, i), OID_LEN), oid)+}++fn copy_key(map: OidMap, i: usize, oid: bytes.Bytes) void = trust {+ @memcpy(oid_ptr(map, i) as ref void, oid.ptr as ref void, OID_LEN)+}++fn copy_value(map: OidMap, i: usize, value: bytes.Bytes) void = trust {+ @memset(value_ptr(map, i) as ref void, 0, VALUE_LEN)+ if value.len > 0 {+ val n: mut usize = value.len+ if n > VALUE_LEN {+ n = VALUE_LEN+ }+ @memcpy(value_ptr(map, i) as ref void, value.ptr as ref void, n)+ }+}++pub fn new(initial: usize) OidMap = trust {+ val cap: usize = round_cap(initial)+ val p: ref u8 = @alloc(cap * SLOT_LEN) as ref u8+ @memset(p as ref void, 0, cap * SLOT_LEN)+ return OidMap{slots: p, cap: cap, len: 0}+}++pub fn free(map: mut OidMap) void = trust {+ if map.slots != none {+ @free(map.slots as ref void)+ }+ map.slots = none+ map.cap = 0+ map.len = 0+}++pub fn count(map: OidMap) usize = trust {+ return map.len+}++fn insert_slot(map: mut OidMap, oid: bytes.Bytes, value: bytes.Bytes) void = trust {+ val mask: usize = map.cap - 1+ val h: u64 = hash_oid(oid)+ val idx: mut usize = (h as usize) & mask+ for {+ if !used_at(map, idx) {+ set_used(map, idx)+ copy_key(map, idx, oid)+ copy_value(map, idx, value)+ map.len+++ return+ }+ if slot_eql(map, idx, oid) {+ copy_value(map, idx, value)+ return+ }+ idx = (idx + 1) & mask+ }+}++fn grow(map: mut OidMap) void = trust {+ val old_slots: mut ref u8 = map.slots+ val old_cap: usize = map.cap+ val new_cap: usize = old_cap * 2+ val p: ref u8 = @alloc(new_cap * SLOT_LEN) as ref u8+ @memset(p as ref void, 0, new_cap * SLOT_LEN)+ map.slots = p+ map.cap = new_cap+ map.len = 0+ val i: mut usize = 0+ for i < old_cap {+ if @load8(@ptradd(old_slots, (i * SLOT_LEN) as i64)) != 0 {+ val op: bytes.Bytes = bytes.bytes(+ @ptradd(old_slots, (i * SLOT_LEN + 1) as i64),+ OID_LEN+ )+ val vp: bytes.Bytes = bytes.bytes(+ @ptradd(old_slots, (i * SLOT_LEN + 1 + OID_LEN) as i64),+ VALUE_LEN+ )+ insert_slot(map, op, vp)+ }+ i+++ }+ @free(old_slots as ref void)+}++/// Insert or replace an entry. An empty `value` records membership only.+pub fn put(map: mut OidMap, oid: bytes.Bytes, value: bytes.Bytes) void = trust {+ pre {+ oid_len: oid.len == OID_LEN+ value_len: value.len == 0 || value.len <= VALUE_LEN+ }+ if (map.len + 1) * 10 >= map.cap * 7 {+ grow(map)+ }+ insert_slot(map, oid, value)+}++pub fn get(map: OidMap, oid: bytes.Bytes) option[bytes.Bytes] = trust {+ pre {+ oid_len: oid.len == OID_LEN+ }+ if map.cap == 0 {+ return none+ }+ val mask: usize = map.cap - 1+ val h: u64 = hash_oid(oid)+ val idx: mut usize = (h as usize) & mask+ for {+ if !used_at(map, idx) {+ return none+ }+ if slot_eql(map, idx, oid) {+ return some bytes.bytes(value_ptr(map, idx), VALUE_LEN)+ }+ idx = (idx + 1) & mask+ }+ return none+}++pub fn contains(map: OidMap, oid: bytes.Bytes) bool = trust {+ if get(map, oid) is some _ {+ return true+ }+ return false+}++pub fn slot_used(map: OidMap, i: usize) bool = trust {+ pre {+ in_bounds: i < map.cap+ }+ return used_at(map, i)+}++pub fn slot_oid(map: OidMap, i: usize) bytes.Bytes = trust {+ pre {+ in_bounds: i < map.cap+ }+ return bytes.bytes(oid_ptr(map, i), OID_LEN)+}++pub fn slot_value(map: OidMap, i: usize) bytes.Bytes = trust {+ pre {+ in_bounds: i < map.cap+ }+ return bytes.bytes(value_ptr(map, i), VALUE_LEN)+}--- /dev/null+++ b/veins/src/git/refs.sx@@ -0,0 +1,284 @@+/// Read refs and HEAD directly from a git directory.++val str = use("std/string")+val bytes = use("../core/bytes.sx")+val lists = use("../core/lists.sx")+val files = use("../io/files.sx")++pub type Ref = {+ name: mut bytes.Bytes+ oid: mut bytes.Bytes+}++pub type RefSet = {+ branches: mut list[ref Ref]+ tags: mut list[ref Ref]+ head: mut bytes.Bytes+}++fn new_ref(name: bytes.Bytes, oid: bytes.Bytes) ref Ref = trust {+ val r: mut ref Ref = @alloc(@sizeof(Ref)) as ref Ref+ r.name = name+ r.oid = oid+ return r+}++fn hex_value(c: u8) i32 = trust {+ 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+}++pub fn parse_hex_oid(text: bytes.Bytes) option[bytes.Bytes] = trust {+ if text.len != 40 {+ return none+ }+ val out: ref u8 = @alloc(20) as ref u8+ val i: mut usize = 0+ for i < 20 {+ val hi: i32 = hex_value(bytes.Bytes.at(text, i * 2))+ val lo: i32 = hex_value(bytes.Bytes.at(text, i * 2 + 1))+ if hi < 0 || lo < 0 {+ @free(out as ref void)+ return none+ }+ @store8(@ptradd(out, i as i64), ((hi * 16 + lo) as u8))+ i+++ }+ return some bytes.bytes(out, 20)+}++fn trim_eol(data: bytes.Bytes) bytes.Bytes = trust {+ val end: mut usize = data.len+ for end > 0 && (bytes.Bytes.at(data, end - 1) == 10 || bytes.Bytes.at(data, end - 1) == 13) {+ end--+ }+ return bytes.Bytes.slice(data, 0, end)+}++fn read_line_file(path: str.StringView) option[bytes.Bytes] = trust {+ val data_opt = files.read_all(path)+ match data_opt {+ some d => {+ return some trim_eol(d)+ }+ none => {+ return none+ }+ }+}++fn starts_with(data: bytes.Bytes, prefix: bytes.Bytes) bool = trust {+ return bytes.Bytes.starts_with(data, prefix)+}++fn find_ref(refs: list[ref Ref], name: bytes.Bytes) option[bytes.Bytes] = trust {+ for r in refs {+ if bytes.Bytes.eql(r.name, name) {+ return some r.oid+ }+ }+ return none+}++fn replace_ref(refs: mut list[ref Ref], name: bytes.Bytes, oid: bytes.Bytes) void = trust {+ val i: mut usize = 0+ for i < @len(refs) {+ val o = @get(refs, i)+ if o is some r {+ if bytes.Bytes.eql(r.name, name) {+ r.oid = oid+ return+ }+ }+ i+++ }+ @append(refs, new_ref(bytes.Bytes.dup(name), oid))+}++fn short_name(full: bytes.Bytes, prefix_len: usize) bytes.Bytes = trust {+ return bytes.Bytes.slice(full, prefix_len, full.len)+}++fn read_packed_refs(+ git_dir: str.StringView,+ branches: mut list[ref Ref],+ tags: mut list[ref Ref]+) void = trust {+ val path: str.StringView = files.join(git_dir, str.from_cstr(c"packed-refs"))+ val data_opt = files.read_all(path)+ files.free_path(path)+ val data: mut bytes.Bytes = bytes.empty()+ match data_opt {+ some d => {+ data = d+ }+ none => {+ return+ }+ }+ val pos: mut usize = 0+ for pos < data.len {+ val end: mut usize = pos+ for end < data.len && bytes.Bytes.at(data, end) != 10 {+ end+++ }+ val line: bytes.Bytes = bytes.Bytes.slice(data, pos, end)+ pos = end + 1+ if line.len == 0 || bytes.Bytes.at(line, 0) == 35 || bytes.Bytes.at(line, 0) == 94 {+ continue+ }+ val space: mut usize = 0+ for space < line.len && bytes.Bytes.at(line, space) != 32 {+ space+++ }+ if space == 0 || space >= line.len {+ continue+ }+ val hex: bytes.Bytes = bytes.Bytes.slice(line, 0, space)+ val name: bytes.Bytes = bytes.Bytes.slice(line, space + 1, line.len)+ val oid_opt = parse_hex_oid(hex)+ if oid_opt is some oid {+ if starts_with(name, bytes.bytes(c"refs/heads/", 11)) {+ replace_ref(branches, short_name(name, 11), oid)+ } elif starts_with(name, bytes.bytes(c"refs/tags/", 10)) {+ replace_ref(tags, short_name(name, 10), oid)+ }+ }+ }+ files.free_buffer(data)+}++fn read_ref_dir(+ base: str.StringView,+ rel: str.StringView,+ refs: mut list[ref Ref]+) void = trust {+ val dir: mut str.StringView = base+ if rel.len != 0 {+ dir = files.join(base, rel)+ }+ val names: list[ref u8] = files.list_dir(dir)+ for n in names {+ val nv: str.StringView = str.from_cstr(n)+ val child_rel: mut str.StringView = files.with_suffix(nv, str.view(none, 0))+ if rel.len != 0 {+ files.free_path(child_rel)+ child_rel = files.join3(rel, str.from_cstr(c"/"), nv)+ }+ val child_path: str.StringView = files.join(base, child_rel)+ if files.exists_dir(child_path) {+ read_ref_dir(base, child_rel, refs)+ } else {+ val content_opt = read_line_file(child_path)+ if content_opt is some content {+ val oid_opt = parse_hex_oid(content)+ if oid_opt is some oid {+ replace_ref(refs, bytes.Bytes.dup(bytes.from_cstr(child_rel.ptr)), oid)+ }+ }+ }+ files.free_path(child_rel)+ files.free_path(child_path)+ }+ files.free_names(names)+ if rel.len != 0 {+ files.free_path(dir)+ }+}++fn resolve_head(+ git_dir: str.StringView,+ branches: list[ref Ref],+ tags: list[ref Ref]+) bytes.Bytes = trust {+ val path: str.StringView = files.join(git_dir, str.from_cstr(c"HEAD"))+ val data_opt = read_line_file(path)+ files.free_path(path)+ val data: mut bytes.Bytes = bytes.empty()+ match data_opt {+ some d => {+ data = d+ }+ none => {+ return bytes.empty()+ }+ }+ if starts_with(data, bytes.bytes(c"ref: ", 5)) {+ val name: bytes.Bytes = bytes.Bytes.slice(data, 5, data.len)+ if starts_with(name, bytes.bytes(c"refs/heads/", 11)) {+ val short: bytes.Bytes = short_name(name, 11)+ val found = find_ref(branches, short)+ if found is some oid {+ files.free_buffer(data)+ return bytes.Bytes.dup(oid)+ }+ }+ if starts_with(name, bytes.bytes(c"refs/tags/", 10)) {+ val short2: bytes.Bytes = short_name(name, 10)+ val found2 = find_ref(tags, short2)+ if found2 is some oid {+ files.free_buffer(data)+ return bytes.Bytes.dup(oid)+ }+ }+ files.free_buffer(data)+ return bytes.empty()+ }+ val oid_opt = parse_hex_oid(data)+ files.free_buffer(data)+ match oid_opt {+ some oid => {+ return oid+ }+ none => {+ return bytes.empty()+ }+ }+}++pub fn read(git_dir: str.StringView) RefSet = trust {+ val branches: mut list[ref Ref] = lists.new[ref Ref]()+ val tags: mut list[ref Ref] = lists.new[ref Ref]()+ read_packed_refs(git_dir, branches, tags)+ val heads_base: str.StringView = files.join(git_dir, str.from_cstr(c"refs/heads"))+ read_ref_dir(heads_base, str.view(none, 0), branches)+ files.free_path(heads_base)+ val tags_base: str.StringView = files.join(git_dir, str.from_cstr(c"refs/tags"))+ read_ref_dir(tags_base, str.view(none, 0), tags)+ files.free_path(tags_base)+ val head: bytes.Bytes = resolve_head(git_dir, branches, tags)+ return RefSet{branches: branches, tags: tags, head: head}+}++fn free_refs(refs: list[ref Ref]) void = trust {+ for r in refs {+ if r.name.ptr != none {+ val np: mut ref void = r.name.ptr as ref void+ @free(np)+ }+ if r.oid.ptr != none {+ val op: mut ref void = r.oid.ptr as ref void+ @free(op)+ }+ val rp: mut ref void = r as ref void+ @free(rp)+ }+ @listfree(refs)+}++pub fn free(set: RefSet) void = trust {+ free_refs(set.branches)+ free_refs(set.tags)+ if set.head.ptr != none {+ val hp: mut ref void = set.head.ptr as ref void+ @free(hp)+ }+}--- /dev/null+++ b/veins/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--+ }+ 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 > 8589934592 {+ 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+++ }+ return true+}--- /dev/null+++ b/veins/src/io/native.sx@@ -0,0 +1,185 @@+/// 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"+extern (C) fn lseek(fd: i32, offset: i64, whence: i32) i64 = "lseek"+extern (C) fn pwrite(fd: i32, buf: ref void, n: usize, offset: i64) i64 = "pwrite"+extern (C) fn read(fd: i32, buf: ref void, n: usize) i64 = "read"+extern (C) fn unlink(path: ref u8) i32 = "unlink"++val O_WRONLY: i32 = 1+val O_RDWR: i32 = 2+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+}++/// Write all of `data` to an already-open descriptor.+pub fn write_fd_all(fd: i32, data: bytes.Bytes) bool = trust {+ return write_all_fd(fd, data)+}++/// Open a file for reading and writing, creating or truncating it.+pub fn open_rw(path: str.StringView) i32 = trust {+ val z: str.ZString = zstr(path)+ if z.ptr == none {+ return -1+ }+ val fd: i32 = open(z.ptr, O_RDWR | O_CREAT | O_TRUNC, MODE)+ free_z(z)+ return fd+}++/// Write at an absolute offset, retrying short writes.+pub fn pwrite_fd_all(fd: i32, offset: i64, data: bytes.Bytes) bool = trust {+ val done: mut usize = 0+ for done < data.len {+ val p: ref void = @ptradd(data.ptr, done as i64) as ref void+ val n: i64 = pwrite(fd, p, data.len - done, offset + done as i64)+ if n <= 0 {+ return false+ }+ done = done + n as usize+ }+ return true+}++/// Read up to `n` bytes into `buf`.+pub fn read_fd(fd: i32, buf: ref u8, n: usize) i64 = trust {+ return read(fd, buf as ref void, n)+}++pub fn seek_set(fd: i32, offset: i64) bool = trust {+ return lseek(fd, offset, 0) == offset+}++pub fn fsync_fd(fd: i32) bool = trust {+ return fsync(fd) == 0+}++pub fn close_fd(fd: i32) void = trust {+ val _ = close(fd)+}++pub fn rename_file(oldp: str.StringView, newp: str.StringView) bool = trust {+ val oz: str.ZString = zstr(oldp)+ val nz: str.ZString = zstr(newp)+ if oz.ptr == none || nz.ptr == none {+ free_z(oz)+ free_z(nz)+ return false+ }+ val rc: i32 = rename(oz.ptr, nz.ptr)+ free_z(oz)+ free_z(nz)+ return rc == 0+}++pub fn delete_file(path: str.StringView) bool = trust {+ val z: str.ZString = zstr(path)+ if z.ptr == none {+ return false+ }+ val rc: i32 = unlink(z.ptr)+ free_z(z)+ return rc == 0+}++/// Flush a directory entry change.+pub fn sync_dir_path(dir: str.StringView) bool = trust {+ return sync_dir(dir)+}++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)+}--- /dev/null+++ b/veins/src/io/stat.sx@@ -0,0 +1,120 @@+/// Minimal `lstat`/`readlink` helpers used by working-copy snapshots.+///+/// The C `struct stat` layout differs by platform, so only the fields the+/// snapshot code needs are read, from the offsets used by the hosted runtimes+/// veins targets.++val str = use("std/string")+val allocators = use("std/allocators")+val bytes = use("../core/bytes.sx")++extern (C) fn lstat(path: ref u8, buf: ref void) i32 = "lstat"+extern (C) fn readlink(path: ref u8, buf: ref u8, n: usize) i64 = "readlink"++pub val KIND_MISSING: u8 = 0+pub val KIND_FILE: u8 = 1+pub val KIND_DIR: u8 = 2+pub val KIND_LINK: u8 = 3++pub type StatInfo = {+ kind: mut u8+ executable: mut bool+ size: mut u64+ mtime_ns: mut u64+ inode: mut u64+}++fn heap() allocators.HeapAllocator = trust {+ return @zeroed+}++fn zstr(p: str.StringView) str.ZString = trust {+ return str.zstr_from[allocators.HeapAllocator](heap(), p)+}++fn free_z(z: str.ZString) void = trust {+ str.zstr_free[allocators.HeapAllocator](heap(), z)+}++fn kind_from_mode(mode: u32) u8 = trust {+ val masked: u32 = mode & 61440+ if masked == 16384 {+ return KIND_DIR+ }+ if masked == 32768 {+ return KIND_FILE+ }+ if masked == 40960 {+ return KIND_LINK+ }+ return KIND_MISSING+}++pub fn read(path: str.StringView) option[StatInfo] = trust {+ val z: str.ZString = zstr(path)+ if z.ptr == none {+ return none+ }+ val buf: ref u8 = @alloc(320) as ref u8+ @memset(buf as ref void, 0, 320)+ val rc: i32 = lstat(z.ptr, buf as ref void)+ free_z(z)+ if rc != 0 {+ @free(buf as ref void)+ return none+ }+ val info: mut StatInfo = StatInfo{+ kind: KIND_MISSING,+ executable: false,+ size: 0,+ mtime_ns: 0,+ inode: 0+ }+ when linux {+ val mode: u32 = @load32(@ptradd(buf, 24) as ref void) as u32+ info.kind = kind_from_mode(mode)+ info.executable = (mode & 73) != 0+ info.inode = @load64(@ptradd(buf, 8) as ref void) as u64+ info.size = @load64(@ptradd(buf, 48) as ref void) as u64+ val sec: u64 = @load64(@ptradd(buf, 88) as ref void) as u64+ val nsec: u64 = @load64(@ptradd(buf, 96) as ref void) as u64+ info.mtime_ns = sec * 1000000000 + nsec+ }+ or when darwin {+ val mode2: u32 = @load16(@ptradd(buf, 4) as ref void) as u32+ info.kind = kind_from_mode(mode2)+ info.executable = (mode2 & 73) != 0+ info.inode = @load64(@ptradd(buf, 8) as ref void) as u64+ info.size = @load64(@ptradd(buf, 96) as ref void) as u64+ val sec2: u64 = @load64(@ptradd(buf, 48) as ref void) as u64+ val nsec2: u64 = @load64(@ptradd(buf, 56) as ref void) as u64+ info.mtime_ns = sec2 * 1000000000 + nsec2+ }+ otherwise {+ info.kind = KIND_FILE+ info.executable = false+ info.inode = 0+ val sz = trust @load64(@ptradd(buf, 48) as ref void) as u64+ info.size = sz+ info.mtime_ns = 0+ }+ @free(buf as ref void)+ return some info+}++/// Read a symlink target. The result is owned by the caller.+pub fn link_target(path: str.StringView) option[bytes.Bytes] = trust {+ val z: str.ZString = zstr(path)+ if z.ptr == none {+ return none+ }+ val cap: usize = 65537+ val buf: ref u8 = @alloc(cap) as ref u8+ val n: i64 = readlink(z.ptr, buf, cap - 1)+ free_z(z)+ if n < 0 {+ @free(buf as ref void)+ return none+ }+ return some bytes.bytes(buf, n as usize)+}--- /dev/null+++ b/veins/src/main.sx@@ -0,0 +1,480 @@+lib "z"+lib "crypto"++val stdio = use("std/stdio")+val str = use("std/string")+val msg = use("core/msg.sx")+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")+val git_cmd = use("cli/git_cmd.sx")+val checkout_cmd = use("cli/checkout_cmd.sx")+val help_cmd = use("cli/help_cmd.sx")+val bench_cmd = use("cli/bench_cmd.sx")+val status_cmd = use("cli/status_cmd.sx")+val log_cmd = use("cli/log_cmd.sx")+val diff_cmd = use("cli/diff_cmd.sx")+val new_cmd = use("cli/new_cmd.sx")+val op_cmd = use("cli/op_cmd.sx")+val lists = use("core/lists.sx")+val layout = use("store/layout.sx")++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 is_flag(a: ref u8) bool = trust {+ if a == none {+ return false+ }+ if @strlen(a) == 0 {+ return false+ }+ return @load8(a) == 45+}++fn run_init(args: list[ref u8], start: usize) i32 = trust {+ val mut_path: mut str.StringView = str.from_cstr(c".")+ val source: mut option[str.StringView] = none+ val i: mut usize = start+ for i < @len(args) {+ val o = @get(args, i)+ if o is some a {+ val av: bytes.Bytes = bytes.from_cstr(a)+ val prefix: bytes.Bytes = bytes.bytes(c"-git-import:", 12)+ if bytes.Bytes.starts_with(av, prefix) {+ if av.len == 12 {+ msg.error_prefix()+ stdio.eprint("-git-import: requires a path\n", {})+ return 1+ }+ val value: bytes.Bytes = bytes.Bytes.slice(av, 12, av.len)+ source = some str.view(value.ptr, value.len as i64)+ } elif av.len > 0 && bytes.Bytes.at(av, 0) == 45 {+ msg.error_prefix()+ stdio.eprint("unknown flag: {s}\n", {str.from_cstr(a)})+ return 1+ } else {+ mut_path = str.from_cstr(a)+ }+ i+++ } else {+ i+++ }+ }+ return init_cmd.run(mut_path, source)+}++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 end_flags: mut bool = false+ val i: mut usize = start+ for i < @len(args) {+ val o = @get(args, i)+ if o is some a {+ if !end_flags && cmd_is(a, c"--", 2) {+ end_flags = true+ } elif !end_flags && (cmd_is(a, c"-v", 2) || cmd_is(a, c"-verbose", 8)) {+ verbose = true+ } elif !end_flags && is_flag(a) {+ msg.error_prefix()+ stdio.eprint("unknown flag: {s}\n", {str.from_cstr(a)})+ return 1+ } else {+ mut_path = str.from_cstr(a)+ }+ }+ i+++ }+ return fsck_cmd.run(mut_path, verbose)+}+++fn open_repo_or_error(path: str.StringView) option[layout.Repo] = trust {+ val repo_opt = layout.discover(path)+ match repo_opt {+ some repo => {+ return some repo+ }+ none => {+ msg.error_prefix()+ stdio.eprint("not a veins repository\n", {})+ return none+ }+ }+}++fn run_status() i32 = trust {+ val repo_opt = open_repo_or_error(str.from_cstr(c"."))+ match repo_opt {+ some repo => {+ val status: i32 = status_cmd.run(repo)+ layout.free_repo(repo)+ return status+ }+ none => {+ return 1+ }+ }+}++fn run_log(args: list[ref u8], start: usize) i32 = trust {+ val rev: mut bytes.Bytes = bytes.empty()+ val col_titles: mut bool = true+ val end_flags: mut bool = false+ val i: mut usize = start+ for i < @len(args) {+ val o = @get(args, i)+ if o is some a {+ if !end_flags && cmd_is(a, c"--", 2) {+ end_flags = true+ } elif !end_flags && (cmd_is(a, c"-r", 2) || cmd_is(a, c"-rev", 4)) {+ if i + 1 < @len(args) {+ val v = @get(args, i + 1)+ if v is some rv {+ rev = bytes.from_cstr(rv)+ i+++ }+ } else {+ msg.error_prefix()+ stdio.eprint("{s} requires a revision\n", {str.from_cstr(a)})+ return 1+ }+ } elif !end_flags && cmd_is(a, c"-no-col-titles", 14) {+ col_titles = false+ } elif !end_flags && is_flag(a) {+ msg.error_prefix()+ stdio.eprint("unknown flag: {s}\n", {str.from_cstr(a)})+ return 1+ } else {+ rev = bytes.from_cstr(a)+ }+ }+ i+++ }+ val repo_opt = open_repo_or_error(str.from_cstr(c"."))+ match repo_opt {+ some repo => {+ val status: i32 = log_cmd.run(repo, rev, col_titles)+ layout.free_repo(repo)+ return status+ }+ none => {+ return 1+ }+ }+}++fn run_diff(args: list[ref u8], start: usize) i32 = trust {+ val revs: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()+ val end_flags: mut bool = false+ val i: mut usize = start+ for i < @len(args) {+ val o = @get(args, i)+ if o is some a {+ if !end_flags && cmd_is(a, c"--", 2) {+ end_flags = true+ } elif !end_flags && (cmd_is(a, c"-r", 2) || cmd_is(a, c"-rev", 4)) {+ if i + 1 < @len(args) {+ val v = @get(args, i + 1)+ if v is some rv {+ @append(revs, bytes.from_cstr(rv))+ i+++ }+ } else {+ msg.error_prefix()+ stdio.eprint("{s} requires a revision\n", {str.from_cstr(a)})+ @listfree(revs)+ return 1+ }+ } elif !end_flags && is_flag(a) {+ msg.error_prefix()+ stdio.eprint("unknown flag: {s}\n", {str.from_cstr(a)})+ @listfree(revs)+ return 1+ } else {+ @append(revs, bytes.from_cstr(a))+ }+ }+ i+++ }+ val repo_opt = open_repo_or_error(str.from_cstr(c"."))+ match repo_opt {+ some repo => {+ val status: i32 = diff_cmd.run(repo, revs)+ layout.free_repo(repo)+ @listfree(revs)+ return status+ }+ none => {+ @listfree(revs)+ return 1+ }+ }+}++fn run_new(args: list[ref u8], start: usize) i32 = trust {+ val revs: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()+ val end_flags: mut bool = false+ val i: mut usize = start+ for i < @len(args) {+ val o = @get(args, i)+ if o is some a {+ if !end_flags && cmd_is(a, c"--", 2) {+ end_flags = true+ } elif !end_flags && is_flag(a) {+ msg.error_prefix()+ stdio.eprint("unknown flag: {s}\n", {str.from_cstr(a)})+ @listfree(revs)+ return 1+ } else {+ @append(revs, bytes.from_cstr(a))+ }+ }+ i+++ }+ val repo_opt = open_repo_or_error(str.from_cstr(c"."))+ match repo_opt {+ some repo => {+ val status: i32 = new_cmd.new_change(repo, revs)+ layout.free_repo(repo)+ @listfree(revs)+ return status+ }+ none => {+ @listfree(revs)+ return 1+ }+ }+}++fn parse_message(args: list[ref u8], start: usize) result[list[bytes.Bytes], i32] = trust {+ val parts: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()+ val end_flags: mut bool = false+ val i: mut usize = start+ for i < @len(args) {+ val o = @get(args, i)+ if o is some a {+ if !end_flags && cmd_is(a, c"--", 2) {+ end_flags = true+ } elif !end_flags && (cmd_is(a, c"-m", 2) || cmd_is(a, c"-message", 8)) {+ if i + 1 < @len(args) {+ val v = @get(args, i + 1)+ if v is some rv {+ @append(parts, bytes.from_cstr(rv))+ i+++ }+ } else {+ msg.error_prefix()+ stdio.eprint("{s} requires a message\n", {str.from_cstr(a)})+ @listfree(parts)+ return err 1+ }+ } elif !end_flags && is_flag(a) {+ msg.error_prefix()+ stdio.eprint("unknown flag: {s}\n", {str.from_cstr(a)})+ @listfree(parts)+ return err 1+ } else {+ @append(parts, bytes.from_cstr(a))+ }+ }+ i+++ }+ return ok parts+}++fn run_describe(args: list[ref u8], start: usize) i32 = trust {+ val parsed = parse_message(args, start)+ val parts: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()+ match parsed {+ ok x => {+ parts = x+ }+ err code => {+ return code+ }+ }+ val repo_opt = open_repo_or_error(str.from_cstr(c"."))+ match repo_opt {+ some repo => {+ val status: i32 = new_cmd.describe(repo, parts)+ layout.free_repo(repo)+ @listfree(parts)+ return status+ }+ none => {+ @listfree(parts)+ return 1+ }+ }+}++fn run_commit(args: list[ref u8], start: usize) i32 = trust {+ val parsed = parse_message(args, start)+ val parts: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()+ match parsed {+ ok x => {+ parts = x+ }+ err code => {+ return code+ }+ }+ val repo_opt = open_repo_or_error(str.from_cstr(c"."))+ match repo_opt {+ some repo => {+ val n: i32 = new_cmd.commit_changes(repo, parts)+ @listfree(parts)+ layout.free_repo(repo)+ return n+ }+ none => {+ @listfree(parts)+ return 1+ }+ }+}++fn run_undo() i32 = trust {+ val repo_opt = open_repo_or_error(str.from_cstr(c"."))+ match repo_opt {+ some repo => {+ val status: i32 = op_cmd.undo(repo)+ layout.free_repo(repo)+ return status+ }+ none => {+ return 1+ }+ }+}++fn run_op(args: list[ref u8], start: usize) i32 = trust {+ val sub_opt = @get(args, start)+ val sub: mut ref u8 = none+ match sub_opt {+ some s => {+ sub = s+ }+ none => {+ msg.error_prefix()+ stdio.eprint("expected an op subcommand (log, restore, revert)\n", {})+ return 1+ }+ }+ val repo_opt = open_repo_or_error(str.from_cstr(c"."))+ val repo: mut layout.Repo = layout.Repo{root: @zeroed}+ match repo_opt {+ some r => {+ repo = r+ }+ none => {+ return 1+ }+ }+ val status: mut i32 = 1+ if cmd_is(sub, c"log", 3) {+ status = op_cmd.log(repo)+ } elif cmd_is(sub, c"restore", 7) {+ val o = @get(args, start + 1)+ if o is some t {+ status = op_cmd.restore(repo, bytes.from_cstr(t))+ } else {+ msg.error_prefix()+ stdio.eprint("op restore requires an operation id\n", {})+ }+ } elif cmd_is(sub, c"revert", 6) {+ val o = @get(args, start + 1)+ if o is some t {+ status = op_cmd.revert(repo, bytes.from_cstr(t))+ } else {+ msg.error_prefix()+ stdio.eprint("op revert requires an operation id\n", {})+ }+ } else {+ msg.error_prefix()+ stdio.eprint("unknown op subcommand: {s}\n", {str.from_cstr(sub)})+ }+ layout.free_repo(repo)+ return status+}++pub fn main() i32 = trust {+ val args: list[ref u8] = @args()+ if @len(args) < 2 {+ help_cmd.usage()+ return 1+ }+ val cmd_opt = @get(args, 1)+ val cmd: mut ref u8 = none+ match cmd_opt {+ some c => {+ cmd = c+ }+ none => {+ help_cmd.usage()+ return 1+ }+ }++ if cmd_is(cmd, c"init", 4) {+ return run_init(args, 2)+ }+ if cmd_is(cmd, c"git", 3) {+ return git_cmd.run(args, 2)+ }+ if cmd_is(cmd, c"checkout", 8) {+ return checkout_cmd.run(args, 2)+ }+ if cmd_is(cmd, c"status", 6) {+ return run_status()+ }+ if cmd_is(cmd, c"log", 3) {+ return run_log(args, 2)+ }+ if cmd_is(cmd, c"diff", 4) {+ return run_diff(args, 2)+ }+ if cmd_is(cmd, c"new", 3) {+ return run_new(args, 2)+ }+ if cmd_is(cmd, c"describe", 8) {+ return run_describe(args, 2)+ }+ if cmd_is(cmd, c"commit", 6) {+ return run_commit(args, 2)+ }+ if cmd_is(cmd, c"undo", 4) {+ return run_undo()+ }+ if cmd_is(cmd, c"op", 2) {+ return run_op(args, 2)+ }+ if cmd_is(cmd, c"fsck", 4) {+ return run_fsck(args, 2)+ }+ if cmd_is(cmd, c"self-test", 9) {+ return selftest_cmd.run()+ }+ if cmd_is(cmd, c"version", 7) || cmd_is(cmd, c"-version", 8) {+ stdio.puts("vn 0.0.1 (veins-store 1)")+ return 0+ }+ if cmd_is(cmd, c"bench-import", 12) {+ return bench_cmd.run(args, 2)+ }+ if cmd_is(cmd, c"help", 4) || cmd_is(cmd, c"-help", 5) || cmd_is(cmd, c"-h", 2) {+ return help_cmd.run(args, 2)+ }++ msg.error_prefix()+ stdio.eprint("unknown command: {s}\n", {str.from_cstr(cmd)})+ help_cmd.usage()+ return 1+}--- /dev/null+++ b/veins/src/object/blob.sx@@ -0,0 +1,300 @@+/// 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+++ }+ 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+++ }+ 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+++ }+ 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+++ }+ 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 = trust {+ 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)+ val ro: mut ref raw.RawObject = raw.raw(types.BLOB, owned)+ ro.id = root.ptr+ @append(objects, ro)+ 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(@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)+ val ro: mut ref raw.RawObject = raw.raw(types.CHUNK, bytes.Bytes.dup(chunk))+ ro.id = cid.ptr+ @append(objects, ro)+ @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)+ val ro: mut ref raw.RawObject = raw.raw(types.BLOB, owned)+ ro.id = nid.ptr+ @append(objects, ro)+ @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/veins/src/object/changeid.sx@@ -0,0 +1,69 @@+/// Lowercase RFC 4648 base32 rendering for change IDs.++val bytes = use("../core/bytes.sx")+val objid = use("../object/id.sx")++fn alphabet() bytes.Bytes = trust {+ return bytes.bytes(c"abcdefghijklmnopqrstuvwxyz234567", 32)+}++/// Full base32 encoding of a 16-byte change ID. No padding is added.+pub fn encode(cid: objid.ChangeId) bytes.Bytes = trust {+ val out: ref u8 = @alloc(32) as ref u8+ val alpha: bytes.Bytes = alphabet()+ val bufv: mut u64 = 0+ val bits: mut usize = 0+ val n: mut usize = 0+ val i: mut usize = 0+ for i < objid.CHANGE_ID_LEN {+ val c: u8 = @load8(@ptradd(cid.ptr, i as i64))+ bufv = (bufv << 8) | (c as u64)+ bits = bits + 8+ for bits >= 5 {+ val shift: usize = bits - 5+ val idx: usize = ((bufv >> shift) & 31) as usize+ @store8(@ptradd(out, n as i64), bytes.Bytes.at(alpha, idx))+ n+++ bits = shift+ }+ if bits == 0 {+ bufv = 0+ } else {+ bufv = bufv & ((1 as u64 << bits) - 1)+ }+ i+++ }+ if bits > 0 {+ val idx2: usize = ((bufv << (5 - bits)) & 31) as usize+ @store8(@ptradd(out, n as i64), bytes.Bytes.at(alpha, idx2))+ n+++ }+ return bytes.bytes(out, n)+}++pub fn prefix_matches(full: bytes.Bytes, text: bytes.Bytes) bool = trust {+ if text.len == 0 || text.len > full.len {+ return false+ }+ val i: mut usize = 0+ for i < text.len {+ val a: u8 = bytes.Bytes.at(full, i)+ val c: u8 = bytes.Bytes.at(text, i)+ val lower: mut u8 = c+ if c >= 65 && c <= 90 {+ lower = (c + 32) as u8+ }+ if a != lower {+ return false+ }+ i+++ }+ return true+}++pub fn free(cid: bytes.Bytes) void = trust {+ if cid.ptr != none {+ val p: mut ref void = cid.ptr as ref void+ @free(p)+ }+}--- /dev/null+++ b/veins/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+++ }+ 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+++ }+ 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+++ }+ 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+++ }+ 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/veins/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+++ }+ 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/veins/src/object/content.sx@@ -0,0 +1,113 @@+/// Materialize a blob into memory for diff and inspection commands.++val bytes = use("../core/bytes.sx")+val buf = use("../core/buf.sx")+val objid = use("../object/id.sx")+val types = use("../object/types.sx")+val blob = use("../object/blob.sx")+val state = use("../store/state.sx")+val store = use("../store/store.sx")+val files = use("../io/files.sx")+val lazy = use("../git/lazy.sx")+val object = use("../git/object.sx")++fn append_blob(+ handles: list[ref store.Handle],+ out: mut buf.Buf,+ id: objid.Id,+ depth: usize,+ git: object.GitRepo,+ has_git: bool+) bool = trust {+ if depth > 64 {+ return false+ }+ if lazy.is_lazy(id) {+ if !has_git {+ return false+ }+ val read = object.read_fast(git, lazy.git_oid(id))+ match read {+ ok o => {+ val read_ok: mut bool = false+ if o.kind == object.KIND_BLOB {+ buf.Buf.put_bytes(out, o.body)+ read_ok = true+ }+ object.free_object(o)+ return read_ok+ }+ err _ => {+ return false+ }+ }+ }+ val body_opt = state.read_body(handles, id, types.BLOB)+ val body: mut bytes.Bytes = bytes.empty()+ match body_opt {+ some b => {+ body = b+ }+ none => {+ return false+ }+ }+ val decoded = blob.decode(body)+ val b: mut ref blob.Blob = none+ match decoded {+ ok x => {+ b = x+ }+ err _ => {+ files.free_buffer(body)+ return false+ }+ }+ val good: mut bool = true+ if b.form == blob.FORM_INLINE {+ buf.Buf.put_bytes(out, b.data)+ } elif b.form == blob.FORM_LEAF {+ for e in b.entries {+ val chunk_opt = state.read_body(handles, e.id, types.CHUNK)+ match chunk_opt {+ some chunk => {+ buf.Buf.put_bytes(out, chunk)+ files.free_buffer(chunk)+ }+ none => {+ good = false+ }+ }+ if !good {+ break+ }+ }+ } else {+ for e in b.entries {+ if !append_blob(handles, out, e.id, depth + 1, git, has_git) {+ good = false+ break+ }+ }+ }+ blob.free_blob(b)+ files.free_buffer(body)+ return good+}++/// Read the full content of a blob. The returned bytes are owned by the caller.+pub fn read_blob(+ handles: list[ref store.Handle],+ id: objid.Id,+ git: object.GitRepo,+ has_git: bool+) option[bytes.Bytes] = trust {+ val out: mut buf.Buf = buf.new(4096)+ val good: bool = append_blob(handles, out, id, 0, git, has_git)+ val result: mut option[bytes.Bytes] = none+ if good {+ result = some(bytes.Bytes.dup(buf.Buf.view(out)))+ }+ buf.Buf.free(out)+ return result+}--- /dev/null+++ b/veins/src/object/graph.sx@@ -0,0 +1,308 @@+/// Commit graph traversal and revision resolution.++val bytes = use("../core/bytes.sx")+val lists = use("../core/lists.sx")+val objid = use("../object/id.sx")+val types = use("../object/types.sx")+val commit = use("../object/commit.sx")+val tree = use("../object/tree.sx")+val treewalk = use("../object/treewalk.sx")+val view = use("../object/view.sx")+val changeid = use("changeid.sx")+val state = use("../store/state.sx")+val store = use("../store/store.sx")+val files = use("../io/files.sx")+val viewops = use("../store/viewops.sx")++pub fn copy_id(id: objid.Id) objid.Id = trust {+ val out: ref u8 = @alloc(32) as ref u8+ @memcpy(out as ref void, id.ptr as ref void, 32)+ return objid.id(out)+}++pub fn contains(ids: list[objid.Id], id: objid.Id) bool = trust {+ for x in ids {+ if objid.Id.eql(x, id) {+ return true+ }+ }+ return false+}++pub fn free_ids(ids: list[objid.Id]) void = trust {+ for id in ids {+ if id.ptr != none {+ val p: mut ref void = id.ptr as ref void+ @free(p)+ }+ }+ @listfree(ids)+}++pub fn roots(v: ref view.View) list[objid.Id] = trust {+ val out: mut list[objid.Id] = lists.new[objid.Id]()+ for h in v.heads {+ if !contains(out, h) {+ @append(out, copy_id(h))+ }+ }+ for bm in v.bookmarks {+ for id in bm.targets.adds {+ if !contains(out, id) {+ @append(out, copy_id(id))+ }+ }+ }+ for t in v.tags {+ if !contains(out, t.target) {+ @append(out, copy_id(t.target))+ }+ }+ for w in v.working_copies {+ if !contains(out, w.target) {+ @append(out, copy_id(w.target))+ }+ }+ return out+}++pub type LoadedCommit = {+ c: mut ref commit.Commit+ body: mut bytes.Bytes+}++pub fn load_commit(+ handles: list[ref store.Handle],+ id: objid.Id+) option[ref LoadedCommit] = trust {+ val body_opt = state.read_body(handles, id, types.COMMIT)+ val body: mut bytes.Bytes = bytes.empty()+ match body_opt {+ some b => {+ body = b+ }+ none => {+ return none+ }+ }+ val decoded = commit.decode(body)+ match decoded {+ ok c => {+ val lc: mut ref LoadedCommit = @alloc(@sizeof(LoadedCommit)) as ref LoadedCommit+ lc.c = c+ lc.body = body+ return some lc+ }+ err _ => {+ files.free_buffer(body)+ return none+ }+ }+}++pub fn free_loaded(lc: ref LoadedCommit) void = trust {+ commit.free_commit(lc.c)+ files.free_buffer(lc.body)+ @free(lc as ref void)+}++/// True when the commit's tree differs from its first parent's tree.+pub fn has_changes(handles: list[ref store.Handle], lc: ref LoadedCommit) bool = trust {+ if @len(lc.c.parents) > 0 {+ val p = @get(lc.c.parents, 0)+ val pid: mut objid.Id = objid.id_none()+ if p is some x {+ pid = x+ }+ val pl_opt = load_commit(handles, pid)+ val changed: mut bool = true+ if pl_opt is some parent {+ changed = !objid.Id.eql(parent.c.root_tree, lc.c.root_tree)+ free_loaded(parent)+ }+ return changed+ }+ val t_opt = treewalk.read_tree(handles, lc.c.root_tree)+ val changed: mut bool = true+ if t_opt is some t {+ changed = @len(t.entries) > 0+ tree.free_tree(t)+ }+ return changed+}++/// Collect all commits reachable from `start`.+pub fn collect(handles: list[ref store.Handle], start: list[objid.Id]) list[objid.Id] = trust {+ val out: mut list[objid.Id] = lists.new[objid.Id]()+ val stack: mut list[objid.Id] = lists.new[objid.Id]()+ for id in start {+ if !contains(out, id) && !contains(stack, id) {+ @append(stack, copy_id(id))+ }+ }+ for @len(stack) > 0 {+ val id: objid.Id = @remove(stack, @len(stack) - 1)+ if contains(out, id) {+ val ip: mut ref void = id.ptr as ref void+ @free(ip)+ continue+ }+ @append(out, id)+ val c_opt = load_commit(handles, id)+ if c_opt is some lc {+ for p in lc.c.parents {+ if !contains(out, p) && !contains(stack, p) {+ @append(stack, copy_id(p))+ }+ }+ free_loaded(lc)+ }+ }+ @listfree(stack)+ return out+}++pub fn all(handles: list[ref store.Handle], v: ref view.View) list[objid.Id] = trust {+ val rs: list[objid.Id] = roots(v)+ val out: list[objid.Id] = collect(handles, rs)+ free_ids(rs)+ return out+}++fn is_hex_char(c: u8) bool = trust {+ return (c >= 48 && c <= 57) || (c >= 97 && c <= 102) || (c >= 65 && c <= 70)+}++fn is_hex_prefix(b: bytes.Bytes) bool = trust {+ if b.len < 4 || b.len > 64 {+ return false+ }+ val i: mut usize = 0+ for i < b.len {+ if !is_hex_char(bytes.Bytes.at(b, i)) {+ return false+ }+ i+++ }+ return true+}++fn id_matches_hex(id: objid.Id, text: bytes.Bytes) bool = trust {+ val hex: ref u8 = objid.Id.hex(id)+ val full: bytes.Bytes = bytes.bytes(hex, 64)+ val matched: bool = changeid.prefix_matches(full, text)+ @free(hex as ref void)+ return matched+}++fn bookmark_target(v: ref view.View, name: bytes.Bytes) option[objid.Id] = trust {+ for bm in v.bookmarks {+ if bytes.Bytes.eql(bm.name, name) {+ if @len(bm.targets.adds) == 1 {+ val o = @get(bm.targets.adds, 0)+ if o is some id {+ return some id+ }+ }+ return none+ }+ }+ return none+}++fn tag_target(v: ref view.View, name: bytes.Bytes) option[objid.Id] = trust {+ for t in v.tags {+ if bytes.Bytes.eql(t.name, name) {+ return some t.target+ }+ }+ return none+}++fn remote_target(v: ref view.View, text: bytes.Bytes) option[objid.Id] = trust {+ for rr in v.remote_refs {+ val joined: usize = rr.remote.len + 1 + rr.name.len+ if joined == text.len {+ val prefix: bytes.Bytes = bytes.Bytes.slice(text, 0, rr.remote.len)+ if bytes.Bytes.eql(prefix, rr.remote) && bytes.Bytes.at(text, rr.remote.len) == 47 {+ val suffix: bytes.Bytes = bytes.Bytes.slice(+ text,+ rr.remote.len + 1,+ text.len+ )+ if bytes.Bytes.eql(suffix, rr.name) {+ return some rr.target+ }+ }+ }+ }+ return none+}++pub fn resolve(+ handles: list[ref store.Handle],+ v: ref view.View,+ rev: bytes.Bytes+) option[objid.Id] = trust {+ if rev.len == 0 || bytes.Bytes.eql(rev, bytes.bytes(c"@", 1)) {+ return viewops.working_copy(v)+ }+ val bm = bookmark_target(v, rev)+ if bm is some id {+ return some id+ }+ val tg = tag_target(v, rev)+ if tg is some id2 {+ return some id2+ }+ val rr = remote_target(v, rev)+ if rr is some id3 {+ return some id3+ }+ val ids: list[objid.Id] = all(handles, v)+ val matches: mut list[objid.Id] = lists.new[objid.Id]()+ if is_hex_prefix(rev) {+ val i: mut usize = 0+ for i < @len(ids) {+ val o = @get(ids, i)+ if o is some id4 {+ if id_matches_hex(id4, rev) {+ @append(matches, copy_id(id4))+ }+ }+ i+++ }+ }+ if @len(matches) == 0 {+ val i2: mut usize = 0+ for i2 < @len(ids) {+ val o = @get(ids, i2)+ if o is some id5 {+ val c_opt = load_commit(handles, id5)+ if c_opt is some lc {+ if lc.c.change_id.ptr != none {+ val encoded: bytes.Bytes = changeid.encode(lc.c.change_id)+ if changeid.prefix_matches(encoded, rev) {+ @append(matches, copy_id(id5))+ }+ changeid.free(encoded)+ }+ free_loaded(lc)+ }+ }+ i2+++ }+ }+ free_ids(ids)+ val result: mut option[objid.Id] = none+ if @len(matches) == 1 {+ val o = @get(matches, 0)+ if o is some only {+ result = some copy_id(only)+ }+ } else {+ // With divergent changes the change ID is ambiguous; callers report it.+ }+ free_ids(matches)+ return result+}--- /dev/null+++ b/veins/src/object/id.sx@@ -0,0 +1,165 @@+/// 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+++ }+}++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+++ }+ 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 + 9)+ buf.Buf.put_raw(b, c"veins/1", 7)+ 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/veins/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+/// `.veins` 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+++ }+ if is_dot_name(b) {+ return false+ }+ val veins: bytes.Bytes = bytes.bytes(c".veins", 6)+ if bytes.Bytes.eql_ascii_ci(b, veins) {+ 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+++ }+ 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+++ }+ return true+}--- /dev/null+++ b/veins/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+++ }+ 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+++ }+ 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+++ }+ 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/veins/src/object/raw.sx@@ -0,0 +1,38 @@+/// 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+ id: mut ref u8+}++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+ o.id = none+ return o+}++pub fn free_objects(objects: list[ref RawObject]) void = {+ for o in objects {+ if o.body.ptr != none {+ val body_ptr: mut ref void = o.body.ptr as ref void+ trust @free(body_ptr)+ }+ if o.id != none {+ val id_ptr: mut ref void = o.id as ref void+ trust @free(id_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/veins/src/object/tree.sx@@ -0,0 +1,155 @@+/// 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]+ body: mut bytes.Bytes+}++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+++ }+ 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]()+ t.body = bytes.empty()+ 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+++ }+ 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+++ }+ 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 = {+ if t.body.ptr != none {+ val bp: mut ref void = t.body.ptr as ref void+ trust @free(bp)+ }+ 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/veins/src/object/treediff.sx@@ -0,0 +1,148 @@+/// Sorted path-level comparison between two trees.++val bytes = use("../core/bytes.sx")+val lists = use("../core/lists.sx")+val objid = use("../object/id.sx")+val treewalk = use("treewalk.sx")+val store = use("../store/store.sx")++pub type Change = {+ path: mut bytes.Bytes+ old_kind: mut u8+ new_kind: mut u8+ old_id: mut objid.Id+ new_id: mut objid.Id+}++fn copy_id(id: objid.Id) objid.Id = trust {+ if id.ptr == none {+ return objid.id(none)+ }+ val out: ref u8 = @alloc(32) as ref u8+ @memcpy(out as ref void, id.ptr as ref void, 32)+ return objid.id(out)+}++fn new_change(+ path: bytes.Bytes,+ old_kind: u8,+ new_kind: u8,+ oid: objid.Id,+ nid: objid.Id+) ref Change = trust {+ val c: mut ref Change = @alloc(@sizeof(Change)) as ref Change+ c.path = path+ c.old_kind = old_kind+ c.new_kind = new_kind+ c.old_id = copy_id(oid)+ c.new_id = copy_id(nid)+ return c+}++pub fn compare(+ handles: list[ref store.Handle],+ old_tree: option[objid.Id],+ new_tree: option[objid.Id]+) list[ref Change] = trust {+ val old = treewalk.flatten_or_empty(handles, old_tree)+ val new = treewalk.flatten_or_empty(handles, new_tree)+ val out: mut list[ref Change] = lists.new[ref Change]()+ val i: mut usize = 0+ val j: mut usize = 0+ for i < @len(old) || j < @len(new) {+ val take: mut i32 = 0+ if i >= @len(old) {+ take = 1+ } elif j >= @len(new) {+ take = -1+ } else {+ val o = @get(old, i)+ val n = @get(new, j)+ val op: mut bytes.Bytes = bytes.empty()+ val np: mut bytes.Bytes = bytes.empty()+ if o is some oo {+ op = oo.path+ }+ if n is some nn {+ np = nn.path+ }+ take = bytes.Bytes.cmp(op, np) as i32+ }+ if take < 0 {+ val o = @get(old, i)+ if o is some e {+ @append(+ out,+ new_change(+ bytes.Bytes.dup(e.path),+ e.kind,+ treewalk.KIND_MISSING,+ e.target,+ objid.id(none)+ )+ )+ }+ i+++ } elif take > 0 {+ val n = @get(new, j)+ if n is some e2 {+ @append(+ out,+ new_change(+ bytes.Bytes.dup(e2.path),+ treewalk.KIND_MISSING,+ e2.kind,+ objid.id(none),+ e2.target+ )+ )+ }+ j+++ } else {+ val o = @get(old, i)+ val n = @get(new, j)+ if o is some e3 {+ if n is some e4 {+ val same: bool = e3.kind == e4.kind && objid.Id.eql(e3.target, e4.target)+ if !same {+ @append(+ out,+ new_change(+ bytes.Bytes.dup(e3.path),+ e3.kind,+ e4.kind,+ e3.target,+ e4.target+ )+ )+ }+ }+ }+ i+++ j+++ }+ }+ treewalk.free_flat(old)+ treewalk.free_flat(new)+ return out+}++pub fn free(changes: list[ref Change]) void = trust {+ for c in changes {+ if c.path.ptr != none {+ val pp: mut ref void = c.path.ptr as ref void+ @free(pp)+ }+ if c.old_id.ptr != none {+ val op: mut ref void = c.old_id.ptr as ref void+ @free(op)+ }+ if c.new_id.ptr != none {+ val np: mut ref void = c.new_id.ptr as ref void+ @free(np)+ }+ val cp: mut ref void = c as ref void+ @free(cp)+ }+ @listfree(changes)+}--- /dev/null+++ b/veins/src/object/treewalk.sx@@ -0,0 +1,287 @@+/// Helpers for reading, flattening, and comparing tree objects.++val bytes = use("../core/bytes.sx")+val lists = use("../core/lists.sx")+val objid = use("../object/id.sx")+val types = use("../object/types.sx")+val tree = use("../object/tree.sx")+val read = use("../store/state.sx")+val store = use("../store/store.sx")+val files = use("../io/files.sx")++pub val KIND_MISSING: u8 = 0++pub type FlatEntry = {+ path: mut bytes.Bytes+ kind: mut u8+ target: mut objid.Id+}++fn copy_id(id: objid.Id) objid.Id = trust {+ val out: ref u8 = @alloc(32) as ref u8+ @memcpy(out as ref void, id.ptr as ref void, 32)+ return objid.id(out)+}++pub fn read_tree(handles: list[ref store.Handle], id: objid.Id) option[ref tree.Tree] = trust {+ val body_opt = read.read_body(handles, id, types.TREE)+ val body: mut bytes.Bytes = bytes.empty()+ match body_opt {+ some b => {+ body = b+ }+ none => {+ return none+ }+ }+ val decoded = tree.decode(body)+ match decoded {+ ok t => {+ t.body = body+ return some t+ }+ err _ => {+ files.free_buffer(body)+ return none+ }+ }+}++pub fn find_name(t: ref tree.Tree, name: bytes.Bytes) i32 = trust {+ val lo: mut usize = 0+ val hi: mut usize = @len(t.entries)+ for lo < hi {+ val mid: usize = lo + (hi - lo) / 2+ val e = @get(t.entries, mid)+ val c: mut i64 = 0+ if e is some entry {+ c = bytes.Bytes.cmp(entry.name, name)+ if c == 0 {+ return mid as i32+ }+ }+ if c < 0 {+ lo = mid + 1+ } else {+ hi = mid+ }+ }+ return -1+}++fn join_path(prefix: bytes.Bytes, name: bytes.Bytes) bytes.Bytes = trust {+ if prefix.len == 0 {+ return bytes.Bytes.dup(name)+ }+ val out: ref u8 = @alloc(prefix.len + 1 + name.len) as ref u8+ @memcpy(out as ref void, prefix.ptr as ref void, prefix.len)+ @store8(@ptradd(out, prefix.len as i64), 47)+ @memcpy(+ @ptradd(out, (prefix.len + 1) as i64) as ref void,+ name.ptr as ref void,+ name.len+ )+ return bytes.bytes(out, prefix.len + 1 + name.len)+}++fn new_flat(path: bytes.Bytes, kind: u8, target: objid.Id) ref FlatEntry = trust {+ val e: mut ref FlatEntry = @alloc(@sizeof(FlatEntry)) as ref FlatEntry+ e.path = path+ e.kind = kind+ e.target = copy_id(target)+ return e+}++fn flatten_into(+ handles: list[ref store.Handle],+ tree_id: objid.Id,+ prefix: bytes.Bytes,+ out: mut list[ref FlatEntry],+ depth: usize+) bool = trust {+ if depth > 4096 {+ return false+ }+ val t_opt = read_tree(handles, tree_id)+ val t: mut ref tree.Tree = none+ match t_opt {+ some x => {+ t = x+ }+ none => {+ return false+ }+ }+ val good: mut bool = true+ for e in t.entries {+ val path: bytes.Bytes = join_path(prefix, e.name)+ if e.kind == tree.KIND_SUBTREE {+ if !flatten_into(handles, e.target, path, out, depth + 1) {+ files.free_buffer(path)+ good = false+ break+ }+ files.free_buffer(path)+ } else {+ @append(out, new_flat(path, e.kind, e.target))+ }+ }+ tree.free_tree(t)+ return good+}++fn entry_at(xs: list[ref FlatEntry], i: usize) ref FlatEntry = trust {+ val o = @get(xs, i)+ if o is some e {+ return e+ }+ assert false+ return none+}++fn merge_sort(+ xs: mut list[ref FlatEntry],+ lo: usize,+ hi: usize,+ tmp: mut list[ref FlatEntry]+) void = trust {+ if hi - lo <= 1 {+ return+ }+ val mid: usize = lo + (hi - lo) / 2+ merge_sort(xs, lo, mid, tmp)+ merge_sort(xs, mid, hi, tmp)+ val i: mut usize = lo+ val j: mut usize = mid+ val k: mut usize = lo+ for k < hi {+ val take_left: mut bool = false+ if i >= mid {+ take_left = false+ } elif j >= hi {+ take_left = true+ } else {+ take_left = bytes.Bytes.cmp(entry_at(xs, i).path, entry_at(xs, j).path) <= 0+ }+ if take_left {+ @set(tmp, k, entry_at(xs, i))+ i+++ } else {+ @set(tmp, k, entry_at(xs, j))+ j+++ }+ k+++ }+ val m: mut usize = lo+ for m < hi {+ @set(xs, m, entry_at(tmp, m))+ m+++ }+}++pub fn sort_flat(xs: mut list[ref FlatEntry]) void = trust {+ val n: usize = @len(xs)+ if n <= 1 {+ return+ }+ val tmp: mut list[ref FlatEntry] = lists.new[ref FlatEntry]()+ val i: mut usize = 0+ for i < n {+ @append(tmp, none)+ i+++ }+ merge_sort(xs, 0, n, tmp)+ @listfree(tmp)+}++/// Flatten a tree into path entries sorted by full path.+pub fn flatten(handles: list[ref store.Handle], tree_id: objid.Id) list[ref FlatEntry] = trust {+ val out: mut list[ref FlatEntry] = lists.new[ref FlatEntry]()+ if !flatten_into(handles, tree_id, bytes.empty(), out, 0) {+ // Return what was collected; callers treat a short list as an error+ // through `tree_conflicted` / direct read failures.+ }+ sort_flat(out)+ return out+}++pub fn flatten_or_empty(+ handles: list[ref store.Handle],+ tree: option[objid.Id]+) list[ref FlatEntry] = trust {+ if tree is some id {+ return flatten(handles, id)+ }+ return lists.new[ref FlatEntry]()+}++pub fn lookup(entries: list[ref FlatEntry], path: bytes.Bytes) option[ref FlatEntry] = trust {+ val lo: mut usize = 0+ val hi: mut usize = @len(entries)+ for lo < hi {+ val mid: usize = lo + (hi - lo) / 2+ val c: i64 = bytes.Bytes.cmp(entry_at(entries, mid).path, path)+ if c == 0 {+ return some entry_at(entries, mid)+ }+ if c < 0 {+ lo = mid + 1+ } else {+ hi = mid+ }+ }+ return none+}++fn conflicted_into(+ handles: list[ref store.Handle],+ tree_id: objid.Id,+ depth: usize+) bool = trust {+ if depth > 4096 {+ return true+ }+ val t_opt = read_tree(handles, tree_id)+ val t: mut ref tree.Tree = none+ match t_opt {+ some x => {+ t = x+ }+ none => {+ return true+ }+ }+ val found: mut bool = false+ for e in t.entries {+ if e.kind == tree.KIND_CONFLICT {+ found = true+ break+ }+ if e.kind == tree.KIND_SUBTREE && conflicted_into(handles, e.target, depth + 1) {+ found = true+ break+ }+ }+ tree.free_tree(t)+ return found+}++pub fn conflicted(handles: list[ref store.Handle], tree_id: objid.Id) bool = trust {+ return conflicted_into(handles, tree_id, 0)+}++pub fn free_flat(xs: list[ref FlatEntry]) void = trust {+ for e in xs {+ if e.path.ptr != none {+ val pp: mut ref void = e.path.ptr as ref void+ @free(pp)+ }+ if e.target.ptr != none {+ val tp: mut ref void = e.target.ptr as ref void+ @free(tp)+ }+ val ep: mut ref void = e as ref void+ @free(ep)+ }+ @listfree(xs)+}--- /dev/null+++ b/veins/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/veins/src/object/view.sx@@ -0,0 +1,403 @@+/// 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+++ }+ 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+++ }+ 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+++ }+ 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+++ }+ 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+++ }+ 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+++ }+ 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+++ }+ 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+++ }+ 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/veins/src/store/fsck.sx@@ -0,0 +1,693 @@+/// `vn fsck`: canonical-form, hash, referential-integrity, and op-log checks.++val str = use("std/string")+val stdio = use("std/stdio")+val msg = use("../core/msg.sx")+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")+val lazy = use("../git/lazy.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, text: str.StringView) void = {+ ctx.errors+++ trust msg.error_prefix()+ trust stdio.eprint("fsck: {s}: {s}\n", {path, text})+}++fn report_id(ctx: mut Ctx, path: str.StringView, text: str.StringView, id: objid.Id) void = {+ ctx.errors+++ val hx: ref u8 = objid.Id.hex(id)+ trust msg.error_prefix()+ trust stdio.eprint("fsck: {s}: {s} {s}\n", {path, text, str.from_cstr(hx)})+ val p: mut ref void = hx as ref void+ trust @free(p)+}++fn warn(ctx: mut Ctx, path: str.StringView, text: str.StringView) void = {+ ctx.warnings+++ if ctx.verbose {+ trust msg.warning_prefix()+ trust stdio.eprint("fsck: {s}: {s}\n", {path, text})+ }+}++fn format_ok(d: bytes.Bytes) bool = {+ val expected: bytes.Bytes = bytes.bytes(c"veins-store 1", 13)+ 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 .veins/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 .veins/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+ }+ if expected == types.BLOB && lazy.is_lazy(id) {+ return true+ }+ 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+++ }+ 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+++ }+ @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+++ }+ i+++ }+}++fn copy_id(id: objid.Id) objid.Id = trust {+ val out: ref u8 = @alloc(32) as ref u8+ @memcpy(out as ref void, id.ptr as ref void, 32)+ return objid.id(out)+}++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, copy_id(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 {+ msg.warning_prefix()+ stdio.eprint("{d} warning(s)\n", {ctx.warnings})+ }+ if ctx.errors == 0 {+ msg.info_prefix()+ stdio.print("fsck: clean\n", {})+ return 0+ }+ msg.error_prefix()+ stdio.eprint("{d} error(s)\n", {ctx.errors})+ return 1+}--- /dev/null+++ b/veins/src/store/idmap.sx@@ -0,0 +1,139 @@+/// Membership set keyed by 32-byte veins object IDs.++val bytes = use("../core/bytes.sx")++pub val ID_LEN: usize = 32+pub val SLOT_LEN: usize = 40++pub type IdSet = {+ slots: mut ref u8+ cap: mut usize+ len: mut usize+}++fn round_cap(n: usize) usize = {+ val c: mut usize = 16+ for c < n {+ c = c * 2+ }+ return c+}++fn key_ptr(set: IdSet, i: usize) ref u8 = trust {+ return @ptradd(set.slots, (i * SLOT_LEN + 1) as i64)+}++fn used_at(set: IdSet, i: usize) bool = trust {+ return @load8(@ptradd(set.slots, (i * SLOT_LEN) as i64)) != 0+}++fn set_used(set: IdSet, i: usize) void = trust {+ @store8(@ptradd(set.slots, (i * SLOT_LEN) as i64), 1)+}++fn hash_id(id: bytes.Bytes) u64 = {+ val h: mut u64 = 1469598103934665603+ val k: mut usize = 0+ for k < ID_LEN {+ h = (h ^ (bytes.Bytes.at(id, k) as u64)) * 1099511628211+ k+++ }+ return h+}++fn slot_eql(set: IdSet, i: usize, id: bytes.Bytes) bool = trust {+ return bytes.Bytes.eql(bytes.bytes(key_ptr(set, i), ID_LEN), id)+}++fn copy_key(set: IdSet, i: usize, id: bytes.Bytes) void = trust {+ @memcpy(key_ptr(set, i) as ref void, id.ptr as ref void, ID_LEN)+}++pub fn new(initial: usize) IdSet = trust {+ val cap: usize = round_cap(initial)+ val p: ref u8 = @alloc(cap * SLOT_LEN) as ref u8+ @memset(p as ref void, 0, cap * SLOT_LEN)+ return IdSet{slots: p, cap: cap, len: 0}+}++pub fn free(set: mut IdSet) void = trust {+ if set.slots != none {+ @free(set.slots as ref void)+ }+ set.slots = none+ set.cap = 0+ set.len = 0+}++fn grow(set: mut IdSet) void = trust {+ val old_slots: mut ref u8 = set.slots+ val old_cap: usize = set.cap+ val new_cap: usize = old_cap * 2+ val p: ref u8 = @alloc(new_cap * SLOT_LEN) as ref u8+ @memset(p as ref void, 0, new_cap * SLOT_LEN)+ set.slots = p+ set.cap = new_cap+ set.len = 0+ val i: mut usize = 0+ for i < old_cap {+ if @load8(@ptradd(old_slots, (i * SLOT_LEN) as i64)) != 0 {+ val id: bytes.Bytes = bytes.bytes(+ @ptradd(old_slots, (i * SLOT_LEN + 1) as i64),+ ID_LEN+ )+ val _ = insert_existing(set, id)+ }+ i+++ }+ @free(old_slots as ref void)+}++fn insert_existing(set: mut IdSet, id: bytes.Bytes) bool = trust {+ val mask: usize = set.cap - 1+ val idx: mut usize = (hash_id(id) as usize) & mask+ for {+ if !used_at(set, idx) {+ set_used(set, idx)+ copy_key(set, idx, id)+ set.len+++ return true+ }+ if slot_eql(set, idx, id) {+ return false+ }+ idx = (idx + 1) & mask+ }+ return false+}++/// Insert `id`. Returns true when it was not already present.+pub fn put(set: mut IdSet, id: bytes.Bytes) bool = trust {+ pre {+ id_len: id.len == ID_LEN+ }+ if (set.len + 1) * 10 >= set.cap * 7 {+ grow(set)+ }+ return insert_existing(set, id)+}++pub fn contains(set: IdSet, id: bytes.Bytes) bool = trust {+ pre {+ id_len: id.len == ID_LEN+ }+ if set.cap == 0 {+ return false+ }+ val mask: usize = set.cap - 1+ val idx: mut usize = (hash_id(id) as usize) & mask+ for {+ if !used_at(set, idx) {+ return false+ }+ if slot_eql(set, idx, id) {+ return true+ }+ idx = (idx + 1) & mask+ }+ return false+}--- /dev/null+++ b/veins/src/store/index.sx@@ -0,0 +1,222 @@+/// 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+++ }++ 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+++ }+ 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+++ }+ 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+++ }+ 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/veins/src/store/layout.sx@@ -0,0 +1,234 @@+/// 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 = 13++fn format_text() bytes.Bytes = {+ return bytes.bytes(c"veins-store 1", 13)+}++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 `.veins/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)), ".veins/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--+ }+ 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 veins_dir(r: Repo) str.StringView = {+ return files.join(root_view(r), ".veins")+}++pub fn packs_dir(r: Repo) str.StringView = {+ return files.join(root_view(r), ".veins/store/packs")+}++pub fn tmp_dir(r: Repo) str.StringView = {+ return files.join(root_view(r), ".veins/store/tmp")+}++pub fn op_heads_dir(r: Repo) str.StringView = {+ return files.join(root_view(r), ".veins/op-heads")+}++pub fn git_dir(r: Repo) str.StringView = {+ return files.join(root_view(r), ".veins/git")+}++pub fn git_map_dir(r: Repo) str.StringView = {+ return files.join(root_view(r), ".veins/git-map")+}++pub fn raw_dir(r: Repo) str.StringView = {+ return files.join(root_view(r), ".veins/git-map/raw")+}++pub fn working_copy_dir(r: Repo) str.StringView = {+ return files.join(root_view(r), ".veins/working-copy")+}++pub fn config_path(r: Repo) str.StringView = {+ return files.join(root_view(r), ".veins/config")+}++pub fn format_path(r: Repo) str.StringView = {+ return files.join(root_view(r), ".veins/format")+}++fn mkdirs_under(r: Repo, sub: str.StringView) bool = {+ val p: str.StringView = files.join(root_view(r), sub)+ if files.exists_dir(p) {+ files.free_path(p)+ return true+ }+ val created: bool = files.mkdir_all(p)+ files.free_path(p)+ return created+}++fn migrate_dir(r: Repo, old_sub: str.StringView, new_sub: str.StringView) bool = {+ val oldp: str.StringView = files.join(root_view(r), old_sub)+ val newp: str.StringView = files.join(root_view(r), new_sub)+ val old_exists: bool = files.exists_dir(oldp)+ val new_exists: bool = files.exists_dir(newp)+ val moved: mut bool = true+ if old_exists && !new_exists {+ moved = files.rename_path(oldp, newp)+ }+ files.free_path(oldp)+ files.free_path(newp)+ return moved+}++fn ensure_layout(r: Repo) bool = {+ if !migrate_dir(r, ".veins/op_heads", ".veins/op-heads") {+ return false+ }+ if !migrate_dir(r, ".veins/working_copy", ".veins/working-copy") {+ return false+ }+ if !mkdirs_under(r, ".veins") {+ return false+ }+ if !mkdirs_under(r, ".veins/store") {+ return false+ }+ if !mkdirs_under(r, ".veins/store/packs") {+ return false+ }+ if !mkdirs_under(r, ".veins/store/tmp") {+ return false+ }+ if !mkdirs_under(r, ".veins/op-heads") {+ return false+ }+ if !mkdirs_under(r, ".veins/git-map") {+ return false+ }+ if !mkdirs_under(r, ".veins/git-map/raw") {+ return false+ }+ if !mkdirs_under(r, ".veins/working-copy") {+ return false+ }+ if !mkdirs_under(r, ".veins/resolutions") {+ return false+ }+ return true+}++/// 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)+ val had_format: bool = files.exists_file(format)+ if had_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+ }+ } else {+ free_repo(repo)+ return err 3+ }+ } else {+ files.free_path(format)+ }++ if !ensure_layout(repo) {+ free_repo(repo)+ return err 4+ }++ if !had_format {+ 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/veins/src/store/pack.sx@@ -0,0 +1,363 @@+/// 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+++ }+ 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+ )+ trust 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/veins/src/store/records.sx@@ -0,0 +1,117 @@+/// Metadata kept per object while a pack and its index are built.++val objid = use("../object/id.sx")+val lists = use("../core/lists.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 ref_at(xs: list[ref RecordMeta], i: usize) ref RecordMeta = {+ val o = @get(xs, i)+ if o is some r {+ return r+ }+ assert false+ return none+}++fn merge_run(+ src: list[ref RecordMeta],+ dst: mut list[ref RecordMeta],+ left: usize,+ mid: usize,+ right: usize+) void = {+ val i: mut usize = left+ val j: mut usize = mid+ val k: mut usize = left+ for k < right {+ val take_left: mut bool = false+ if i >= mid {+ take_left = false+ } elif j >= right {+ take_left = true+ } else {+ take_left = objid.Id.cmp(ref_at(src, i).id, ref_at(src, j).id) <= 0+ }+ if take_left {+ @set(dst, k, ref_at(src, i))+ i+++ } else {+ @set(dst, k, ref_at(src, j))+ j+++ }+ k+++ }+}++/// Stable bottom-up merge sort by object ID.+pub fn sort_by_id(records: mut list[ref RecordMeta]) void = trust {+ val n: usize = @len(records)+ if n < 2 {+ return+ }+ val src: mut list[ref RecordMeta] = lists.new[ref RecordMeta]()+ val dst: mut list[ref RecordMeta] = lists.new[ref RecordMeta]()+ val i: mut usize = 0+ for i < n {+ val o = @get(records, i)+ if o is some r {+ @append(src, r)+ @append(dst, r)+ } else {+ @append(src, none)+ @append(dst, none)+ }+ i+++ }+ val mut_a: mut list[ref RecordMeta] = src+ val mut_b: mut list[ref RecordMeta] = dst+ val width: mut usize = 1+ for width < n {+ val left: mut usize = 0+ for left < n {+ val mid: mut usize = n+ if left + width < n {+ mid = left + width+ }+ val right: mut usize = n+ if left + 2 * width < n {+ right = left + 2 * width+ }+ merge_run(mut_a, mut_b, left, mid, right)+ left = left + 2 * width+ }+ val tmp: list[ref RecordMeta] = mut_a+ mut_a = mut_b+ mut_b = tmp+ width = width * 2+ }+ val j: mut usize = 0+ for j < n {+ @set(records, j, ref_at(mut_a, j))+ j+++ }+ @listfree(src)+ @listfree(dst)+}--- /dev/null+++ b/veins/src/store/state.sx@@ -0,0 +1,265 @@+/// Read the current operation/view state and advance operation heads.++val str = use("std/string")+val bytes = use("../core/bytes.sx")+val lists = use("../core/lists.sx")+val objid = use("../object/id.sx")+val types = use("../object/types.sx")+val operation = use("../object/operation.sx")+val view = use("../object/view.sx")+val store = use("../store/store.sx")+val layout = use("../store/layout.sx")+val files = use("../io/files.sx")+val native = use("../io/native.sx")++pub fn read_body(+ handles: list[ref store.Handle],+ id: objid.Id,+ expected: u8+) option[bytes.Bytes] = trust {+ val loc: mut store.Loc = store.Loc{pack_index: 0, record_index: 0, kind: 0}+ if !store.find_handles(handles, id, loc) {+ return none+ }+ if loc.kind != expected {+ return none+ }+ val body_opt = store.get_handles(handles, loc)+ val body: mut bytes.Bytes = bytes.empty()+ match body_opt {+ ok b => {+ body = b+ }+ err _ => {+ return none+ }+ }+ val computed: objid.Id = objid.object_id(expected, body)+ val same: bool = objid.Id.eql(computed, id)+ if computed.ptr != none {+ val cp: mut ref void = computed.ptr as ref void+ @free(cp)+ }+ if !same {+ files.free_buffer(body)+ return none+ }+ return some body+}++pub fn read_view(handles: list[ref store.Handle], id: objid.Id) option[ref view.View] = trust {+ val body_opt = read_body(handles, id, types.VIEW)+ val body: mut bytes.Bytes = bytes.empty()+ match body_opt {+ some b => {+ body = b+ }+ none => {+ return none+ }+ }+ val decoded = view.decode(body)+ match decoded {+ ok v => {+ return some v+ }+ err _ => {+ files.free_buffer(body)+ return none+ }+ }+}++pub fn read_operation(+ handles: list[ref store.Handle],+ id: objid.Id+) option[ref operation.Operation] = trust {+ val body_opt = read_body(handles, id, types.OPERATION)+ val body: mut bytes.Bytes = bytes.empty()+ match body_opt {+ some b => {+ body = b+ }+ none => {+ return none+ }+ }+ val decoded = operation.decode(body)+ match decoded {+ ok op => {+ return some op+ }+ err _ => {+ files.free_buffer(body)+ return none+ }+ }+}++fn parse_head_name(name: ref u8) option[objid.Id] = trust {+ val n: i64 = @strlen(name)+ if n != 64 {+ return none+ }+ val raw: ref u8 = @alloc(32) as ref u8+ val i: mut usize = 0+ for i < 32 {+ val hex: bytes.Bytes = bytes.bytes(name, 64)+ val hi_c: u8 = bytes.Bytes.at(hex, i * 2)+ val lo_c: u8 = bytes.Bytes.at(hex, i * 2 + 1)+ val hi: mut i32 = -1+ val lo: mut i32 = -1+ if hi_c >= 48 && hi_c <= 57 {+ hi = (hi_c - 48) as i32+ } elif hi_c >= 97 && hi_c <= 102 {+ hi = (hi_c - 87) as i32+ } elif hi_c >= 65 && hi_c <= 70 {+ hi = (hi_c - 55) as i32+ }+ if lo_c >= 48 && lo_c <= 57 {+ lo = (lo_c - 48) as i32+ } elif lo_c >= 97 && lo_c <= 102 {+ lo = (lo_c - 87) as i32+ } elif lo_c >= 65 && lo_c <= 70 {+ lo = (lo_c - 55) as i32+ }+ if hi < 0 || lo < 0 {+ @free(raw as ref void)+ return none+ }+ @store8(@ptradd(raw, i as i64), ((hi * 16 + lo) as u8))+ i+++ }+ return some objid.id(raw)+}++fn sort_ids(ids: mut list[objid.Id]) void = trust {+ val n: usize = @len(ids)+ val i: mut usize = 1+ for i < n {+ val cur = @get(ids, i)+ val cid: mut objid.Id = objid.id_none()+ if cur is some v {+ cid = v+ }+ val j: mut usize = i+ for j > 0 {+ val prev_opt = @get(ids, j - 1)+ val prev: mut objid.Id = objid.id_none()+ if prev_opt is some v2 {+ prev = v2+ }+ if objid.Id.cmp(prev, cid) <= 0 {+ break+ }+ @set(ids, j, prev)+ j--+ }+ @set(ids, j, cid)+ i+++ }+}++pub fn heads(repo: layout.Repo) list[objid.Id] = trust {+ val out: mut list[objid.Id] = lists.new[objid.Id]()+ val dir: str.StringView = layout.op_heads_dir(repo)+ if !files.exists_dir(dir) {+ files.free_path(dir)+ return out+ }+ val names: list[ref u8] = files.list_dir(dir)+ for n in names {+ val parsed = parse_head_name(n)+ if parsed is some id {+ @append(out, id)+ }+ }+ files.free_names(names)+ files.free_path(dir)+ sort_ids(out)+ return out+}++pub fn current_view(+ repo: layout.Repo,+ handles: list[ref store.Handle]+) option[ref view.View] = trust {+ val hs: list[objid.Id] = heads(repo)+ if @len(hs) == 0 {+ return none+ }+ val first = @get(hs, 0)+ val op_id: mut objid.Id = objid.id_none()+ if first is some v {+ op_id = v+ }+ val op_opt = read_operation(handles, op_id)+ match op_opt {+ some op => {+ val v_opt = read_view(handles, op.view)+ operation.free_operation(op)+ for h in hs {+ if h.ptr != none {+ val hp: mut ref void = h.ptr as ref void+ @free(hp)+ }+ }+ @listfree(hs)+ return v_opt+ }+ none => {+ for h in hs {+ if h.ptr != none {+ val hp2: mut ref void = h.ptr as ref void+ @free(hp2)+ }+ }+ @listfree(hs)+ return none+ }+ }+}++pub fn empty_view() ref view.View = trust {+ val v: mut ref view.View = @alloc(@sizeof(view.View)) as ref view.View+ v.heads = lists.new[objid.Id]()+ v.bookmarks = lists.new[ref view.Bookmark]()+ v.tags = lists.new[ref view.TagRef]()+ v.remote_refs = lists.new[ref view.RemoteRef]()+ v.working_copies = lists.new[ref view.WorkspaceRef]()+ return v+}++pub fn head_name(id: objid.Id) ref u8 = trust {+ return objid.Id.hex(id)+}++pub fn write_head(repo: layout.Repo, id: objid.Id) bool = trust {+ val hex: ref u8 = head_name(id)+ val dir: str.StringView = layout.op_heads_dir(repo)+ val name: str.StringView = str.from_cstr(hex)+ val final: str.StringView = files.join(dir, name)+ val tmpd: str.StringView = layout.tmp_dir(repo)+ val tmpname: str.StringView = files.with_suffix(name, str.from_cstr(c".tmp"))+ val tmp: str.StringView = files.join(tmpd, tmpname)+ val success: bool = native.write_atomic(tmp, final, tmpd, dir, bytes.empty())+ files.free_path(dir)+ files.free_path(tmpd)+ files.free_path(final)+ files.free_path(tmpname)+ files.free_path(tmp)+ @free(hex as ref void)+ return success+}++pub fn delete_head(repo: layout.Repo, id: objid.Id) bool = trust {+ val hex: ref u8 = head_name(id)+ val dir: str.StringView = layout.op_heads_dir(repo)+ val name: str.StringView = str.from_cstr(hex)+ val path: str.StringView = files.join(dir, name)+ val success: bool = files.delete(path)+ files.free_path(dir)+ files.free_path(path)+ @free(hex as ref void)+ return success+}--- /dev/null+++ b/veins/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+++ }+ 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+++ }+ 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/veins/src/store/txn.sx@@ -0,0 +1,476 @@+/// Operation transactions: load the current view, append objects and a new+/// operation to a single pack, then advance the operation heads.++val stdio = use("std/stdio")+val msg = use("../core/msg.sx")+val os = use("std/os")+val time = use("std/time")+val bytes = use("../core/bytes.sx")+val lists = use("../core/lists.sx")+val prim = use("../core/primitives.sx")+val objid = use("../object/id.sx")+val types = use("../object/types.sx")+val operation = use("../object/operation.sx")+val view = use("../object/view.sx")+val writer = use("../store/writer.sx")+val store = use("../store/store.sx")+val state = use("../store/state.sx")+val layout = use("../store/layout.sx")++pub type Txn = {+ repo: mut layout.Repo+ writer: mut ref writer.Writer+ view: mut ref view.View+ parents: mut list[objid.Id]+ start_ms: mut i64+}++fn copy_id(id: objid.Id) objid.Id = trust {+ val out: ref u8 = @alloc(32) as ref u8+ @memcpy(out as ref void, id.ptr as ref void, 32)+ return objid.id(out)+}++fn free_ids(ids: list[objid.Id]) void = trust {+ for id in ids {+ if id.ptr != none {+ val p: mut ref void = id.ptr as ref void+ @free(p)+ }+ }+ @listfree(ids)+}++fn same_id(a: objid.Id, b: objid.Id) bool = trust {+ return objid.Id.eql(a, b)+}++fn contains_id(xs: list[objid.Id], id: objid.Id) bool = trust {+ for x in xs {+ if same_id(x, id) {+ return true+ }+ }+ return false+}++fn add_unique(xs: mut list[objid.Id], id: objid.Id) void = trust {+ if !contains_id(xs, id) {+ @append(xs, copy_id(id))+ }+}++fn clone_targets(ts: view.TargetSet) view.TargetSet = trust {+ val out: mut view.TargetSet = view.empty_target_set()+ for a in ts.adds {+ @append(out.adds, copy_id(a))+ }+ for r in ts.removes {+ @append(out.removes, copy_id(r))+ }+ return out+}++fn clone_bookmark(bm: ref view.Bookmark) ref view.Bookmark = trust {+ val b: mut ref view.Bookmark = @alloc(@sizeof(view.Bookmark)) as ref view.Bookmark+ b.name = bytes.Bytes.dup(bm.name)+ b.targets = clone_targets(bm.targets)+ return b+}++fn clone_tag(t: ref view.TagRef) ref view.TagRef = trust {+ val out: mut ref view.TagRef = @alloc(@sizeof(view.TagRef)) as ref view.TagRef+ out.name = bytes.Bytes.dup(t.name)+ out.target = copy_id(t.target)+ return out+}++fn clone_workspace(w: ref view.WorkspaceRef) ref view.WorkspaceRef = trust {+ val out: mut ref view.WorkspaceRef = @alloc(@sizeof(view.WorkspaceRef)) as ref view.WorkspaceRef+ out.workspace = bytes.Bytes.dup(w.workspace)+ out.target = copy_id(w.target)+ return out+}++fn find_bookmark(v: ref view.View, name: bytes.Bytes) i32 = trust {+ val i: mut usize = 0+ for i < @len(v.bookmarks) {+ val o = @get(v.bookmarks, i)+ if o is some bm {+ if bytes.Bytes.eql(bm.name, name) {+ return i as i32+ }+ }+ i+++ }+ return -1+}++fn find_tag(v: ref view.View, name: bytes.Bytes) i32 = trust {+ val i: mut usize = 0+ for i < @len(v.tags) {+ val o = @get(v.tags, i)+ if o is some t {+ if bytes.Bytes.eql(t.name, name) {+ return i as i32+ }+ }+ i+++ }+ return -1+}++fn find_workspace(v: ref view.View, name: bytes.Bytes) i32 = trust {+ val i: mut usize = 0+ for i < @len(v.working_copies) {+ val o = @get(v.working_copies, i)+ if o is some w {+ if bytes.Bytes.eql(w.workspace, name) {+ return i as i32+ }+ }+ i+++ }+ return -1+}++fn conflict_targets(a: objid.Id, b: objid.Id) view.TargetSet = trust {+ val ts: mut view.TargetSet = view.empty_target_set()+ @append(ts.adds, copy_id(a))+ @append(ts.adds, copy_id(b))+ @append(ts.removes, objid.id(none))+ return ts+}++fn merge_view_into(dst: mut ref view.View, src: ref view.View) void = trust {+ for h in src.heads {+ add_unique(dst.heads, h)+ }+ for bm in src.bookmarks {+ val idx: i32 = find_bookmark(dst, bm.name)+ if idx < 0 {+ @append(dst.bookmarks, clone_bookmark(bm))+ } else {+ val existing = @get(dst.bookmarks, idx as usize)+ if existing is some e {+ val a: mut objid.Id = objid.id_none()+ val b: mut objid.Id = objid.id_none()+ if @len(e.targets.adds) > 0 {+ val o = @get(e.targets.adds, 0)+ if o is some id {+ a = id+ }+ }+ if @len(bm.targets.adds) > 0 {+ val o2 = @get(bm.targets.adds, 0)+ if o2 is some id2 {+ b = id2+ }+ }+ if !same_id(a, b) || @len(e.targets.adds) != @len(bm.targets.adds) {+ @listfree(e.targets.adds)+ @listfree(e.targets.removes)+ e.targets = conflict_targets(a, b)+ }+ }+ }+ }+ for t in src.tags {+ if find_tag(dst, t.name) < 0 {+ @append(dst.tags, clone_tag(t))+ }+ }+ for w in src.working_copies {+ if find_workspace(dst, w.workspace) < 0 {+ @append(dst.working_copies, clone_workspace(w))+ }+ }+}++fn sort_bookmarks(xs: mut list[ref view.Bookmark]) void = trust {+ val i: mut usize = 1+ for i < @len(xs) {+ val cur = @get(xs, i)+ val c: mut ref view.Bookmark = none+ if cur is some v {+ c = v+ }+ val j: mut usize = i+ for j > 0 {+ val prev_opt = @get(xs, j - 1)+ val prev: mut ref view.Bookmark = none+ if prev_opt is some v2 {+ prev = v2+ }+ if bytes.Bytes.cmp(prev.name, c.name) <= 0 {+ break+ }+ @set(xs, j, prev)+ j--+ }+ @set(xs, j, c)+ i+++ }+}++fn sort_tags(xs: mut list[ref view.TagRef]) void = trust {+ val i: mut usize = 1+ for i < @len(xs) {+ val cur = @get(xs, i)+ val c: mut ref view.TagRef = none+ if cur is some v {+ c = v+ }+ val j: mut usize = i+ for j > 0 {+ val prev_opt = @get(xs, j - 1)+ val prev: mut ref view.TagRef = none+ if prev_opt is some v2 {+ prev = v2+ }+ if bytes.Bytes.cmp(prev.name, c.name) <= 0 {+ break+ }+ @set(xs, j, prev)+ j--+ }+ @set(xs, j, c)+ i+++ }+}++fn sort_workspaces(xs: mut list[ref view.WorkspaceRef]) void = trust {+ val i: mut usize = 1+ for i < @len(xs) {+ val cur = @get(xs, i)+ val c: mut ref view.WorkspaceRef = none+ if cur is some v {+ c = v+ }+ val j: mut usize = i+ for j > 0 {+ val prev_opt = @get(xs, j - 1)+ val prev: mut ref view.WorkspaceRef = none+ if prev_opt is some v2 {+ prev = v2+ }+ if bytes.Bytes.cmp(prev.workspace, c.workspace) <= 0 {+ break+ }+ @set(xs, j, prev)+ j--+ }+ @set(xs, j, c)+ i+++ }+}++fn load_view_for_head(+ handles: list[ref store.Handle],+ id: objid.Id+) option[ref view.View] = trust {+ val op_opt = state.read_operation(handles, id)+ val op: mut ref operation.Operation = none+ match op_opt {+ some o => {+ op = o+ }+ none => {+ return none+ }+ }+ val view_id: objid.Id = copy_id(op.view)+ operation.free_operation(op)+ val v_opt = state.read_view(handles, view_id)+ if view_id.ptr != none {+ val vp: mut ref void = view_id.ptr as ref void+ @free(vp)+ }+ return v_opt+}++pub fn begin(repo: layout.Repo) option[ref Txn] = trust {+ val heads: list[objid.Id] = state.heads(repo)+ val st: store.Store = store.open_all(repo)+ val v: mut ref view.View = none+ if @len(heads) == 0 {+ v = state.empty_view()+ } elif @len(heads) == 1 {+ val only = @get(heads, 0)+ val id: mut objid.Id = objid.id_none()+ if only is some x {+ id = x+ }+ val loaded = load_view_for_head(st.handles, id)+ match loaded {+ some x => {+ v = x+ }+ none => {+ store.close(st)+ free_ids(heads)+ return none+ }+ }+ } else {+ val first = @get(heads, 0)+ val first_id: mut objid.Id = objid.id_none()+ if first is some x {+ first_id = x+ }+ val base = load_view_for_head(st.handles, first_id)+ val base_view: mut ref view.View = none+ match base {+ some x => {+ base_view = x+ }+ none => {+ store.close(st)+ free_ids(heads)+ return none+ }+ }+ val i: mut usize = 1+ for i < @len(heads) {+ val o = @get(heads, i)+ val hid: mut objid.Id = objid.id_none()+ if o is some x {+ hid = x+ }+ val extra = load_view_for_head(st.handles, hid)+ if extra is some ev {+ merge_view_into(base_view, ev)+ view.free_view(ev)+ }+ i+++ }+ add_unique(base_view.heads, first_id)+ v = base_view+ }+ store.close(st)+ sort_bookmarks(v.bookmarks)+ sort_tags(v.tags)+ sort_workspaces(v.working_copies)+ val w_opt = writer.open(repo)+ val w: mut ref writer.Writer = none+ match w_opt {+ some x => {+ w = x+ }+ none => {+ view.free_view(v)+ free_ids(heads)+ return none+ }+ }+ val tx: mut ref Txn = @alloc(@sizeof(Txn)) as ref Txn+ tx.repo = repo+ tx.writer = w+ tx.view = v+ tx.parents = heads+ tx.start_ms = time.unix_now_millis()+ return some tx+}++pub fn add_object(tx: mut ref Txn, kind: u8, body: bytes.Bytes) objid.Id = trust {+ return writer.add(tx.writer, kind, body)+}++pub fn add_known(tx: mut ref Txn, kind: u8, id: objid.Id, body: bytes.Bytes) objid.Id = trust {+ return writer.add_known(tx.writer, kind, id, body)+}++fn host_from_env() bytes.Bytes = trust {+ val h = os.env(c"HOSTNAME")+ match h {+ some v => {+ return bytes.Bytes.dup(bytes.from_cstr(v))+ }+ none => {+ return bytes.Bytes.dup(bytes.bytes(c"localhost", 9))+ }+ }+}++fn user_from_env() bytes.Bytes = trust {+ val u = os.env(c"USER")+ match u {+ some v => {+ return bytes.Bytes.dup(bytes.from_cstr(v))+ }+ none => {+ return bytes.Bytes.dup(bytes.bytes(c"unknown", 7))+ }+ }+}++fn free_txn(tx: mut ref Txn) void = trust {+ if tx.view != none {+ view.free_view(tx.view)+ }+ free_ids(tx.parents)+ @free(tx as ref void)+}++pub fn abort(tx: mut ref Txn) void = trust {+ writer.abort(tx.writer)+ free_txn(tx)+}++/// Encode the view, write an operation, and advance the heads.+pub fn finish(tx: mut ref Txn, description: bytes.Bytes) i32 = trust {+ val view_body: bytes.Bytes = view.encode(tx.view)+ val view_id: objid.Id = writer.add(tx.writer, types.VIEW, view_body)+ val now: i64 = time.unix_now_millis()+ val hostname: bytes.Bytes = host_from_env()+ val username: bytes.Bytes = user_from_env()+ val tags: mut list[ref prim.KeyValue] = lists.new[ref prim.KeyValue]()+ val kv: mut ref prim.KeyValue = @alloc(@sizeof(prim.KeyValue)) as ref prim.KeyValue+ kv.key = bytes.bytes(c"command", 7)+ kv.value = bytes.Bytes.dup(description)+ @append(tags, kv)+ val op: mut ref operation.Operation = @alloc(@sizeof(operation.Operation)) as ref operation.Operation+ op.parents = lists.new[objid.Id]()+ for p in tx.parents {+ @append(op.parents, copy_id(p))+ }+ op.view = view_id+ op.start = prim.TimeMs{ms: tx.start_ms, tz_min: 0}+ op.end = prim.TimeMs{ms: now, tz_min: 0}+ op.hostname = hostname+ op.username = username+ op.description = bytes.Bytes.dup(description)+ op.tags = tags+ val op_body: bytes.Bytes = operation.encode(op)+ val op_id: objid.Id = writer.add(tx.writer, types.OPERATION, op_body)+ operation.free_operation(op)++ val wrote: bool = writer.finish(tx.writer)+ if !wrote {+ msg.error_prefix()+ stdio.eprint("failed to write object pack\n", {})+ free_txn(tx)+ return 1+ }+ val head_ok: bool = state.write_head(tx.repo, op_id)+ if head_ok {+ for p in tx.parents {+ if !objid.Id.is_none(p) {+ val _ = state.delete_head(tx.repo, p)+ }+ }+ }+ if view_id.ptr != none {+ val vp: mut ref void = view_id.ptr as ref void+ @free(vp)+ }+ if op_id.ptr != none {+ val opp: mut ref void = op_id.ptr as ref void+ @free(opp)+ }+ free_txn(tx)+ if !head_ok {+ return 1+ }+ return 0+}--- /dev/null+++ b/veins/src/store/viewops.sx@@ -0,0 +1,166 @@+/// Small view mutations shared by working-copy and operation commands.++val bytes = use("../core/bytes.sx")+val lists = use("../core/lists.sx")+val objid = use("../object/id.sx")+val view = use("../object/view.sx")++pub fn copy_id(id: objid.Id) objid.Id = trust {+ val out: ref u8 = @alloc(32) as ref u8+ @memcpy(out as ref void, id.ptr as ref void, 32)+ return objid.id(out)+}++pub fn same(a: objid.Id, b: objid.Id) bool = trust {+ return objid.Id.eql(a, b)+}++pub fn contains(xs: list[objid.Id], id: objid.Id) bool = trust {+ for x in xs {+ if same(x, id) {+ return true+ }+ }+ return false+}++pub fn add_unique(xs: mut list[objid.Id], id: objid.Id) void = trust {+ if !contains(xs, id) {+ @append(xs, copy_id(id))+ }+}++pub fn workspace_name() bytes.Bytes = trust {+ return bytes.bytes(c"default", 7)+}++pub fn working_copy(v: ref view.View) option[objid.Id] = trust {+ val name: bytes.Bytes = workspace_name()+ for w in v.working_copies {+ if bytes.Bytes.eql(w.workspace, name) {+ return some copy_id(w.target)+ }+ }+ return none+}++pub fn set_workspace(v: mut ref view.View, id: objid.Id) void = trust {+ val name: bytes.Bytes = workspace_name()+ val i: mut usize = 0+ for i < @len(v.working_copies) {+ val o = @get(v.working_copies, i)+ if o is some w {+ if bytes.Bytes.eql(w.workspace, name) {+ w.target = copy_id(id)+ return+ }+ }+ i+++ }+ val w2: mut ref view.WorkspaceRef = @alloc(@sizeof(view.WorkspaceRef)) as ref view.WorkspaceRef+ w2.workspace = bytes.Bytes.dup(name)+ w2.target = copy_id(id)+ @append(v.working_copies, w2)+ sort_workspaces(v.working_copies)+}++pub fn remove_head(v: mut ref view.View, id: objid.Id) void = trust {+ val i: mut usize = 0+ for i < @len(v.heads) {+ val o = @get(v.heads, i)+ if o is some h {+ if same(h, id) {+ @remove(v.heads, i)+ return+ }+ }+ i+++ }+}++fn sort_heads(xs: mut list[objid.Id]) void = trust {+ val i: mut usize = 1+ for i < @len(xs) {+ val cur = @get(xs, i)+ val c: mut objid.Id = objid.id_none()+ if cur is some v {+ c = v+ }+ val j: mut usize = i+ for j > 0 {+ val prev_opt = @get(xs, j - 1)+ val prev: mut objid.Id = objid.id_none()+ if prev_opt is some v2 {+ prev = v2+ }+ if objid.Id.cmp(prev, c) <= 0 {+ break+ }+ @set(xs, j, prev)+ j--+ }+ @set(xs, j, c)+ i+++ }+}++pub fn rebuild_heads(v: mut ref view.View) void = trust {+ for bm in v.bookmarks {+ for id in bm.targets.adds {+ add_unique(v.heads, id)+ }+ }+ for t in v.tags {+ add_unique(v.heads, t.target)+ }+ for w in v.working_copies {+ add_unique(v.heads, w.target)+ }+ sort_heads(v.heads)+}++pub fn bookmark_names(v: ref view.View, id: objid.Id) list[bytes.Bytes] = trust {+ val out: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()+ for bm in v.bookmarks {+ if contains(bm.targets.adds, id) {+ @append(out, bm.name)+ }+ }+ return out+}++pub fn tag_names(v: ref view.View, id: objid.Id) list[bytes.Bytes] = trust {+ val out: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()+ for t in v.tags {+ if same(t.target, id) {+ @append(out, t.name)+ }+ }+ return out+}++pub fn sort_workspaces(xs: mut list[ref view.WorkspaceRef]) void = trust {+ val i: mut usize = 1+ for i < @len(xs) {+ val cur = @get(xs, i)+ val c: mut ref view.WorkspaceRef = none+ if cur is some v {+ c = v+ }+ val j: mut usize = i+ for j > 0 {+ val prev_opt = @get(xs, j - 1)+ val prev: mut ref view.WorkspaceRef = none+ if prev_opt is some v2 {+ prev = v2+ }+ if bytes.Bytes.cmp(prev.workspace, c.workspace) <= 0 {+ break+ }+ @set(xs, j, prev)+ j--+ }+ @set(xs, j, c)+ i+++ }+}--- /dev/null+++ b/veins/src/store/writer.sx@@ -0,0 +1,456 @@+/// Streaming pack writer used by the git importer.+///+/// Records are appended to a temporary file as they are produced. At finish,+/// the header count is patched, the pack trailer is hashed by streaming over+/// the file, and the index is written from the collected record metadata.++val str = use("std/string")+val time = use("std/time")+val allocators = use("std/allocators")+val thread = use("std/thread")+val bytes = use("../core/bytes.sx")+val buf = use("../core/buf.sx")+val lists = use("../core/lists.sx")+val objid = use("../object/id.sx")+val records = use("records.sx")+val idmap = use("idmap.sx")+val index = use("index.sx")+val zstd = use("zstd.sx")+val layout = use("../store/layout.sx")+val files = use("../io/files.sx")+val native = use("../io/native.sx")+val b3 = use("../crypto/blake3.sx")++extern (C) fn sysconf(name: i32) i64 = "sysconf"++type PendingRecord = {+ id: mut objid.Id+ kind: mut u8+ body: mut bytes.Bytes+ stored: mut bytes.Bytes+ comp: mut u8+}++type CompressJob = {+ items: mut list[ref PendingRecord]+ start: mut usize+ step: mut usize+}++pub type Writer = {+ tmp_path: mut str.StringView+ tmp_dir: mut str.StringView+ packs_dir: mut str.StringView+ fd: mut i32+ count: mut usize+ offset: mut u64+ metas: mut list[ref records.RecordMeta]+ items: mut list[ref PendingRecord]+ pending_bytes: mut usize+ failed: mut bool+ seen: mut idmap.IdSet+}++fn worker_count() usize = trust {+ when linux {+ val n: i64 = sysconf(84)+ if n > 0 {+ return n as usize+ }+ }+ when macos {+ val n2: i64 = sysconf(58)+ if n2 > 0 {+ return n2 as usize+ }+ }+ return 4+}++fn free_items(items: list[ref PendingRecord]) void = trust {+ for r in items {+ if r.body.ptr != none {+ val bp: mut ref void = r.body.ptr as ref void+ @free(bp)+ }+ if r.comp == 1 && r.stored.ptr != none {+ val sp: mut ref void = r.stored.ptr as ref void+ @free(sp)+ }+ if r.id.ptr != none {+ val ip: mut ref void = r.id.ptr as ref void+ @free(ip)+ }+ val rp: mut ref void = r as ref void+ @free(rp)+ }+ @listfree(items)+}++fn compress_worker(arg: ref void) ref void = trust {+ val job: ref CompressJob = arg as ref CompressJob+ val i: mut usize = job.start+ for i < @len(job.items) {+ val item = @get(job.items, i)+ if item is some r {+ val compressed: bytes.Bytes = zstd.compress(r.body, zstd.DEFAULT_LEVEL)+ if compressed.len > 0 {+ r.comp = 1+ r.stored = compressed+ } else {+ r.comp = 0+ r.stored = r.body+ }+ }+ i = i + job.step+ }+ return none+}++fn compress_items(items: list[ref PendingRecord]) void = trust {+ val n: usize = @len(items)+ if n == 0 {+ return+ }+ val workers: mut usize = worker_count()+ if workers < 1 {+ workers = 1+ }+ if workers > n {+ workers = n+ }+ val ac: allocators.HeapAllocator = @zeroed+ val thread_refs: mut list[ref void] = lists.new[ref void]()+ val jobs: mut list[ref CompressJob] = lists.new[ref CompressJob]()+ val w: mut usize = 0+ for w < workers {+ val job: mut ref CompressJob = @alloc(@sizeof(CompressJob)) as ref CompressJob+ job.items = items+ job.start = w+ job.step = workers+ @append(jobs, job)+ val tr = thread.Thread.new[allocators.HeapAllocator](ac, compress_worker, job as ref void)+ match tr {+ ok t => {+ @append(thread_refs, t)+ }+ err _ => {+ compress_worker(job as ref void)+ }+ }+ w+++ }+ val j: mut usize = 0+ for j < @len(thread_refs) {+ val tr = @get(thread_refs, j)+ if tr is some t {+ val joined = thread.Thread.join[allocators.HeapAllocator](ac, t)+ match joined {+ ok _ => {+ }+ err _ => {+ }+ }+ }+ j+++ }+ for job in jobs {+ val _ = job+ }+ @listfree(jobs)+ @listfree(thread_refs)+}++fn copy_id(id: objid.Id) objid.Id = trust {+ val out: ref u8 = @alloc(32) as ref u8+ @memcpy(out as ref void, id.ptr as ref void, 32)+ return objid.id(out)+}++fn free_meta_list(metas: list[ref records.RecordMeta]) void = trust {+ for m in metas {+ if m.id.ptr != none {+ val ip: mut ref void = m.id.ptr as ref void+ @free(ip)+ }+ val mp: mut ref void = m as ref void+ @free(mp)+ }+ @listfree(metas)+}++pub fn open(repo: layout.Repo) option[ref Writer] = trust {+ val tmpdir: str.StringView = layout.tmp_dir(repo)+ val packs: str.StringView = layout.packs_dir(repo)+ val name_c: ref u8 = @fmtalloc("import-{d}.vpack", {time.now_ns()})+ val name: str.StringView = str.from_cstr(name_c)+ val tmp: str.StringView = files.join(tmpdir, name)+ @free(name_c as ref void)+ val fd: i32 = native.open_rw(tmp)+ if fd < 0 {+ files.free_path(tmpdir)+ files.free_path(packs)+ files.free_path(tmp)+ return none+ }+ val header: mut buf.Buf = buf.new(16)+ buf.Buf.put_raw(header, c"VPK1", 4)+ buf.Buf.put_u32_le(header, 1)+ buf.Buf.put_u64_le(header, 0)+ val wrote: bool = native.write_fd_all(fd, buf.Buf.view(header))+ if !wrote {+ buf.Buf.free(header)+ native.close_fd(fd)+ val _ = native.delete_file(tmp)+ files.free_path(tmpdir)+ files.free_path(packs)+ files.free_path(tmp)+ return none+ }+ val w: mut ref Writer = @alloc(@sizeof(Writer)) as ref Writer+ w.tmp_path = tmp+ w.tmp_dir = tmpdir+ w.packs_dir = packs+ w.fd = fd+ w.count = 0+ w.offset = 16+ w.metas = lists.new[ref records.RecordMeta]()+ w.items = lists.new[ref PendingRecord]()+ w.pending_bytes = 0+ buf.Buf.free(header)+ w.failed = false+ w.seen = idmap.new(1024)+ return some w+}++/// Append one object with a precomputed ID. Takes ownership of `body`.+pub fn add_known(w: mut Writer, kind: u8, id: objid.Id, body: bytes.Bytes) objid.Id = trust {+ if w.failed {+ if body.ptr != none {+ val bp: mut ref void = body.ptr as ref void+ @free(bp)+ }+ return id+ }+ val id_view: bytes.Bytes = bytes.bytes(id.ptr, 32)+ if idmap.contains(w.seen, id_view) {+ if body.ptr != none {+ val bp2: mut ref void = body.ptr as ref void+ @free(bp2)+ }+ return id+ }+ val _ = idmap.put(w.seen, id_view)+ val r: mut ref PendingRecord = @alloc(@sizeof(PendingRecord)) as ref PendingRecord+ r.id = copy_id(id)+ r.kind = kind+ r.body = body+ r.stored = bytes.empty()+ r.comp = 0+ @append(w.items, r)+ w.pending_bytes = w.pending_bytes + body.len+ if w.pending_bytes >= 268435456 {+ if !write_pending(w) {+ w.failed = true+ }+ }+ return id+}++/// Append one object. Takes ownership of `body`.+pub fn add(w: mut Writer, kind: u8, body: bytes.Bytes) objid.Id = trust {+ val id: objid.Id = objid.object_id(kind, body)+ return add_known(w, kind, id, body)+}++fn free_writer(w: mut ref Writer) void = trust {+ if w.fd >= 0 {+ native.close_fd(w.fd)+ w.fd = -1+ }+ free_meta_list(w.metas)+ if @len(w.items) > 0 {+ free_items(w.items)+ } else {+ @listfree(w.items)+ }+ idmap.free(w.seen)+ if w.tmp_path.ptr != none {+ files.free_path(w.tmp_path)+ }+ if w.tmp_dir.ptr != none {+ files.free_path(w.tmp_dir)+ }+ if w.packs_dir.ptr != none {+ files.free_path(w.packs_dir)+ }+ @free(w as ref void)+}++pub fn abort(w: mut ref Writer) void = trust {+ if !w.failed {+ w.failed = true+ }+ if w.fd >= 0 {+ native.close_fd(w.fd)+ w.fd = -1+ }+ val _ = native.delete_file(w.tmp_path)+ free_writer(w)+}++fn write_pending(w: mut ref Writer) bool = trust {+ if @len(w.items) == 0 {+ return true+ }+ compress_items(w.items)+ val i: mut usize = 0+ val out: mut buf.Buf = buf.new(8388608)+ val header: mut buf.Buf = buf.new(64)+ for i < @len(w.items) {+ val item = @get(w.items, i)+ if item is some r {+ buf.Buf.reset(header)+ buf.Buf.put_id(header, r.id.ptr)+ buf.Buf.put_u8(header, r.kind)+ buf.Buf.put_u8(header, r.comp)+ buf.Buf.put_varint(header, r.body.len as u64)+ buf.Buf.put_varint(header, r.stored.len as u64)+ val start: u64 = w.offset+ buf.Buf.put_bytes(out, buf.Buf.view(header))+ buf.Buf.put_bytes(out, r.stored)+ @append(w.metas, records.record_meta(copy_id(r.id), start, r.kind, r.body.len as u64))+ w.count+++ w.offset = start + header.len as u64 + r.stored.len as u64+ if out.len >= 8388608 {+ if !native.write_fd_all(w.fd, buf.Buf.view(out)) {+ w.failed = true+ }+ buf.Buf.reset(out)+ }+ }+ i+++ }+ if out.len > 0 {+ if !native.write_fd_all(w.fd, buf.Buf.view(out)) {+ w.failed = true+ }+ buf.Buf.reset(out)+ }+ buf.Buf.free(out)+ buf.Buf.free(header)+ if w.failed {+ return false+ }+ free_items(w.items)+ w.items = lists.new[ref PendingRecord]()+ w.pending_bytes = 0+ return true+}++/// Finish the pack and write its index. `w` is consumed.+pub fn finish(w: mut ref Writer) bool = trust {+ if w.failed {+ abort(w)+ return false+ }+ if !write_pending(w) {+ abort(w)+ return false+ }++ val count_buf: mut buf.Buf = buf.new(8)+ buf.Buf.put_u64_le(count_buf, w.count as u64)+ val patched: bool = native.pwrite_fd_all(w.fd, 8, buf.Buf.view(count_buf))+ buf.Buf.free(count_buf)+ if !patched {+ abort(w)+ return false+ }++ if !native.seek_set(w.fd, 0) {+ abort(w)+ return false+ }+ val state: ref void = @alloc(b3.hasher_state_size())+ b3.hasher_init(state)+ val chunk: ref u8 = @alloc(1048576) as ref u8+ val hashed: mut bool = true+ for {+ val n: i64 = native.read_fd(w.fd, chunk, 1048576)+ if n < 0 {+ hashed = false+ break+ }+ if n == 0 {+ break+ }+ b3.hasher_update(state, chunk, n as usize)+ }+ val digest: ref u8 = @alloc(32) as ref u8+ b3.hasher_final(state, digest)+ @free(state)+ @free(chunk as ref void)+ if !hashed {+ @free(digest as ref void)+ abort(w)+ return false+ }+ val trailer: bytes.Bytes = bytes.bytes(digest, 32)+ val wrote_trailer: bool = native.pwrite_fd_all(w.fd, w.offset as i64, trailer)+ val synced: bool = native.fsync_fd(w.fd)+ native.close_fd(w.fd)+ w.fd = -1+ if !wrote_trailer || !synced {+ @free(digest as ref void)+ val _ = native.delete_file(w.tmp_path)+ free_writer(w)+ return false+ }++ val hex: ref u8 = @alloc(65) as ref u8+ objid.hex_encode(digest, 32, hex)+ @store8(@ptradd(hex, 64), 0)+ val pack_name: str.StringView = str.from_cstr(hex)+ val pack_file: str.StringView = files.with_suffix(pack_name, str.from_cstr(c".vpack"))+ val idx_file: str.StringView = files.with_suffix(pack_name, str.from_cstr(c".vidx"))+ val pack_final: str.StringView = files.join(w.packs_dir, pack_file)+ val idx_final: str.StringView = files.join(w.packs_dir, idx_file)+ val renamed: bool = native.rename_file(w.tmp_path, pack_final)+ if !renamed {+ @free(hex as ref void)+ @free(digest as ref void)+ files.free_path(pack_file)+ files.free_path(idx_file)+ files.free_path(pack_final)+ files.free_path(idx_final)+ val _ = native.delete_file(w.tmp_path)+ free_writer(w)+ return false+ }+ val _ = native.sync_dir_path(w.packs_dir)++ records.sort_by_id(w.metas)+ val index_bytes: bytes.Bytes = index.encode(w.metas, trailer)+ val idx_tmp_name: str.StringView = files.with_suffix(pack_name, str.from_cstr(c".vidx.tmp"))+ val idx_tmp: str.StringView = files.join(w.tmp_dir, idx_tmp_name)+ val wrote_index: bool = native.write_atomic(+ idx_tmp,+ idx_final,+ w.tmp_dir,+ w.packs_dir,+ index_bytes+ )+ val idx_buf: mut ref void = index_bytes.ptr as ref void+ @free(idx_buf)+ files.free_path(idx_tmp_name)+ files.free_path(idx_tmp)+ files.free_path(pack_file)+ files.free_path(idx_file)+ files.free_path(pack_final)+ files.free_path(idx_final)+ @free(hex as ref void)+ @free(digest as ref void)+ free_writer(w)+ return wrote_index+}--- /dev/null+++ b/veins/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 = 1++/// 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)+}--- /dev/null+++ b/veins/src/worktree/checkout.sx@@ -0,0 +1,919 @@+/// Parallel, path-safe checkout from a veins tree into the working directory.++val str = use("std/string")+val stdio = use("std/stdio")+val msg = use("../core/msg.sx")+val allocators = use("std/allocators")+val thread = use("std/thread")+val bytes = use("../core/bytes.sx")+val lists = use("../core/lists.sx")+val objid = use("../object/id.sx")+val types = use("../object/types.sx")+val names = use("../object/names.sx")+val blob = use("../object/blob.sx")+val tree = use("../object/tree.sx")+val commit = use("../object/commit.sx")+val view = use("../object/view.sx")+val store = use("../store/store.sx")+val layout = use("../store/layout.sx")+val state = use("../store/state.sx")+val files = use("../io/files.sx")+val native = use("../io/native.sx")+val object = use("../git/object.sx")+val lazy = use("../git/lazy.sx")++extern (C) fn openat(dirfd: i32, path: ref u8, flags: i32, mode: i32) i32 = "openat"+extern (C) fn mkdirat(dirfd: i32, path: ref u8, mode: i32) i32 = "mkdirat"+extern (C) fn symlinkat(target: ref u8, newdirfd: i32, linkpath: ref u8) i32 = "symlinkat"+extern (C) fn unlinkat(dirfd: i32, path: ref u8, flags: i32) i32 = "unlinkat"+extern (C) fn close(fd: i32) i32 = "close"+extern (C) fn fchmod(fd: i32, mode: u32) i32 = "fchmod"+extern (C) fn sysconf(name: i32) i64 = "sysconf"++fn o_wronly() i32 = trust {+ return 1+}++fn o_creat() i32 = trust {+ when linux {+ return 64+ }+ when macos {+ return 512+ }+ return 64+}++fn o_trunc() i32 = trust {+ when linux {+ return 512+ }+ when macos {+ return 1024+ }+ return 512+}++fn o_nofollow() i32 = trust {+ when linux {+ return 131072+ }+ when macos {+ return 256+ }+ return 0+}++fn o_directory() i32 = trust {+ when linux {+ return 65536+ }+ when macos {+ return 1048576+ }+ return 0+}++fn o_cloexec() i32 = trust {+ when linux {+ return 524288+ }+ when macos {+ return 16777216+ }+ return 0+}++val DIR_MODE: u32 = 493+val FILE_MODE: u32 = 420+val EXEC_MODE: u32 = 493++fn cpu_count() usize = trust {+ when linux {+ val n: i64 = sysconf(84)+ if n > 0 {+ return n as usize+ }+ }+ when macos {+ val n2: i64 = sysconf(58)+ if n2 > 0 {+ return n2 as usize+ }+ }+ return 4+}++pub type CheckoutTask = {+ path: mut bytes.Bytes+ kind: mut u8+ target: mut objid.Id+}++pub type CheckoutWalk = {+ handles: list[ref store.Handle]+ tasks: mut list[ref CheckoutTask]+ dirs: mut list[bytes.Bytes]+ failed: mut bool+ error: mut bytes.Bytes+}++pub type CheckoutJob = {+ handles: mut list[ref store.Handle]+ root_fd: mut i32+ tasks: mut list[ref CheckoutTask]+ start: mut usize+ step: mut usize+ failed: mut bool+ error: mut bytes.Bytes+ git: mut object.GitRepo+ git_lock: mut ref void+ has_git: mut bool+}++type CheckoutTarget = {+ fd: i32+ name: ref u8+ owned_fd: bool+}++fn copy_id(id: objid.Id) objid.Id = trust {+ val out: ref u8 = @alloc(32) as ref u8+ @memcpy(out as ref void, id.ptr as ref void, 32)+ return objid.id(out)+}++fn join_bytes(prefix: bytes.Bytes, name: bytes.Bytes) bytes.Bytes = trust {+ if prefix.len == 0 {+ return bytes.Bytes.dup(name)+ }+ val out: ref u8 = @alloc(prefix.len + 1 + name.len) as ref u8+ @memcpy(out as ref void, prefix.ptr as ref void, prefix.len)+ @store8(@ptradd(out, prefix.len as i64), 47)+ @memcpy(@ptradd(out, (prefix.len + 1) as i64) as ref void, name.ptr as ref void, name.len)+ return bytes.bytes(out, prefix.len + 1 + name.len)+}++fn component_cstr(path: bytes.Bytes, start: usize, end: usize) ref u8 = trust {+ val n: usize = end - start+ val out: ref u8 = @alloc(n + 1) as ref u8+ if n > 0 {+ @memcpy(out as ref void, @ptradd(path.ptr, start as i64) as ref void, n)+ }+ @store8(@ptradd(out, n as i64), 0)+ return out+}++fn next_slash(path: bytes.Bytes, start: usize) usize = trust {+ val i: mut usize = start+ for i < path.len && bytes.Bytes.at(path, i) != 47 {+ i+++ }+ return i+}++fn valid_checkout_name(name: bytes.Bytes) bool = trust {+ if !names.valid_name(name) {+ return false+ }+ if bytes.Bytes.eql_ascii_ci(name, bytes.bytes(c".git", 4)) {+ return false+ }+ return true+}++fn ensure_dir(root_fd: i32, path: bytes.Bytes) bool = trust {+ val pos: mut usize = 0+ val cur: mut i32 = root_fd+ val owned: mut bool = false+ for pos < path.len {+ val end: usize = next_slash(path, pos)+ if end == pos {+ if owned {+ close(cur)+ }+ return false+ }+ val comp: ref u8 = component_cstr(path, pos, end)+ val flags: i32 = o_directory() | o_nofollow() | o_cloexec()+ val next: mut i32 = openat(cur, comp, flags, 0)+ if next < 0 {+ val made: i32 = mkdirat(cur, comp, DIR_MODE as i32)+ if made != 0 {+ next = openat(cur, comp, flags, 0)+ } else {+ next = openat(cur, comp, flags, 0)+ }+ }+ @free(comp as ref void)+ if next < 0 {+ if owned {+ close(cur)+ }+ return false+ }+ if owned {+ close(cur)+ }+ cur = next+ owned = true+ if end == path.len {+ break+ }+ pos = end + 1+ }+ if owned {+ close(cur)+ }+ return true+}++fn open_parent(root_fd: i32, path: bytes.Bytes) option[CheckoutTarget] = trust {+ val last_slash: mut i64 = -1+ val i: mut usize = 0+ for i < path.len {+ if bytes.Bytes.at(path, i) == 47 {+ last_slash = i as i64+ }+ i+++ }+ val cur: mut i32 = root_fd+ val owned: mut bool = false+ if last_slash >= 0 {+ val pos: mut usize = 0+ val stop: usize = last_slash as usize+ for pos < stop {+ val end: usize = next_slash(path, pos)+ if end == pos || end > stop {+ if owned {+ close(cur)+ }+ return none+ }+ val comp: ref u8 = component_cstr(path, pos, end)+ val next: i32 = openat(cur, comp, o_directory() | o_nofollow() | o_cloexec(), 0)+ @free(comp as ref void)+ if next < 0 {+ if owned {+ close(cur)+ }+ return none+ }+ if owned {+ close(cur)+ }+ cur = next+ owned = true+ pos = end + 1+ }+ }+ val name_start: mut usize = 0+ if last_slash >= 0 {+ name_start = last_slash as usize + 1+ }+ if name_start >= path.len {+ if owned {+ close(cur)+ }+ return none+ }+ val name: ref u8 = component_cstr(path, name_start, path.len)+ return some CheckoutTarget{fd: cur, name: name, owned_fd: owned}+}++fn close_target(t: CheckoutTarget) void = trust {+ if t.owned_fd {+ close(t.fd)+ }+ val np: mut ref void = t.name as ref void+ @free(np)+}++fn read_git_blob(+ git: object.GitRepo,+ lock: ref void,+ has_git: bool,+ blob_id: objid.Id+) option[bytes.Bytes] = trust {+ if !has_git || lock == none {+ return none+ }+ thread.Mutex.lock(lock)+ val read = object.read_fast(git, lazy.git_oid(blob_id))+ val out: mut option[bytes.Bytes] = none+ match read {+ ok o => {+ if o.kind == object.KIND_BLOB {+ out = some bytes.Bytes.dup(o.body)+ }+ object.free_object(o)+ }+ err _ => {+ }+ }+ thread.Mutex.unlock(lock)+ return out+}++fn write_blob_data(+ handles: list[ref store.Handle],+ fd: i32,+ blob_id: objid.Id,+ depth: usize,+ git: object.GitRepo,+ git_lock: ref void,+ has_git: bool+) bool = trust {+ if depth > 64 {+ return false+ }+ if lazy.is_lazy(blob_id) {+ val git_body = read_git_blob(git, git_lock, has_git, blob_id)+ match git_body {+ some b => {+ val wrote: bool = native.write_fd_all(fd, b)+ files.free_buffer(b)+ return wrote+ }+ none => {+ return false+ }+ }+ }+ val body_opt = state.read_body(handles, blob_id, types.BLOB)+ val body: mut bytes.Bytes = bytes.empty()+ match body_opt {+ some b => {+ body = b+ }+ none => {+ return false+ }+ }+ val decoded = blob.decode(body)+ val b: mut ref blob.Blob = none+ match decoded {+ ok x => {+ b = x+ }+ err _ => {+ files.free_buffer(body)+ return false+ }+ }+ val success: mut bool = true+ if b.form == blob.FORM_INLINE {+ success = native.write_fd_all(fd, b.data)+ } elif b.form == blob.FORM_LEAF {+ for e in b.entries {+ val chunk_opt = state.read_body(handles, e.id, types.CHUNK)+ match chunk_opt {+ some chunk => {+ if !native.write_fd_all(fd, chunk) {+ success = false+ }+ files.free_buffer(chunk)+ }+ none => {+ success = false+ }+ }+ if !success {+ break+ }+ }+ } else {+ for e in b.entries {+ if !write_blob_data(handles, fd, e.id, depth + 1, git, git_lock, has_git) {+ success = false+ break+ }+ }+ }+ blob.free_blob(b)+ files.free_buffer(body)+ return success+}++fn write_symlink(+ handles: list[ref store.Handle],+ t: CheckoutTarget,+ blob_id: objid.Id,+ git: object.GitRepo,+ git_lock: ref void,+ has_git: bool+) bool = trust {+ if lazy.is_lazy(blob_id) {+ val git_body = read_git_blob(git, git_lock, has_git, blob_id)+ match git_body {+ some b => {+ val target: ref u8 = @alloc(b.len + 1) as ref u8+ if b.len > 0 {+ @memcpy(target as ref void, b.ptr as ref void, b.len)+ }+ @store8(@ptradd(target, b.len as i64), 0)+ val _ = unlinkat(t.fd, t.name, 0)+ val created: bool = symlinkat(target, t.fd, t.name) == 0+ @free(target as ref void)+ files.free_buffer(b)+ return created+ }+ none => {+ return false+ }+ }+ }+ val body_opt = state.read_body(handles, blob_id, types.BLOB)+ val body: mut bytes.Bytes = bytes.empty()+ match body_opt {+ some b => {+ body = b+ }+ none => {+ return false+ }+ }+ val decoded = blob.decode(body)+ val b: mut ref blob.Blob = none+ match decoded {+ ok x => {+ b = x+ }+ err _ => {+ files.free_buffer(body)+ return false+ }+ }+ val success: mut bool = false+ if b.form == blob.FORM_INLINE {+ val target: ref u8 = @alloc(b.data.len + 1) as ref u8+ if b.data.len > 0 {+ @memcpy(target as ref void, b.data.ptr as ref void, b.data.len)+ }+ @store8(@ptradd(target, b.data.len as i64), 0)+ val _ = unlinkat(t.fd, t.name, 0)+ success = symlinkat(target, t.fd, t.name) == 0+ @free(target as ref void)+ }+ blob.free_blob(b)+ files.free_buffer(body)+ return success+}++fn write_task(job: ref CheckoutJob, task: ref CheckoutTask) bool = trust {+ val target_opt = open_parent(job.root_fd, task.path)+ match target_opt {+ some t => {+ val success: mut bool = false+ if task.kind == tree.KIND_SYMLINK {+ success = write_symlink(+ job.handles,+ t,+ task.target,+ job.git,+ job.git_lock,+ job.has_git+ )+ } else {+ val flags: i32 = o_wronly() | o_creat() | o_trunc() | o_nofollow() | o_cloexec()+ val mode: u32 = FILE_MODE+ val mut_fd: mut i32 = openat(t.fd, t.name, flags, mode as i32)+ if mut_fd < 0 {+ val _ = unlinkat(t.fd, t.name, 0)+ mut_fd = openat(t.fd, t.name, flags, mode as i32)+ }+ val fd: i32 = mut_fd+ if fd >= 0 {+ success = write_blob_data(+ job.handles,+ fd,+ task.target,+ 0,+ job.git,+ job.git_lock,+ job.has_git+ )+ if success {+ val want: mut u32 = FILE_MODE+ if task.kind == tree.KIND_EXECUTABLE {+ want = EXEC_MODE+ }+ if fchmod(fd, want) != 0 {+ success = false+ }+ }+ close(fd)+ }+ }+ close_target(t)+ return success+ }+ none => {+ return false+ }+ }+}++fn checkout_worker(arg: ref void) ref void = trust {+ val job: mut ref CheckoutJob = arg as ref CheckoutJob+ val i: mut usize = job.start+ for i < @len(job.tasks) {+ val item = @get(job.tasks, i)+ if item is some task {+ if !write_task(job, task) {+ job.failed = true+ job.error = bytes.Bytes.dup(task.path)+ break+ }+ }+ i = i + job.step+ }+ return none+}++fn add_task(+ walk: mut CheckoutWalk,+ path: bytes.Bytes,+ kind: u8,+ target: objid.Id+) void = trust {+ val t: mut ref CheckoutTask = @alloc(@sizeof(CheckoutTask)) as ref CheckoutTask+ t.path = path+ t.kind = kind+ t.target = copy_id(target)+ @append(walk.tasks, t)+}++fn walk_tree(+ walk: mut CheckoutWalk,+ tree_id: objid.Id,+ prefix: bytes.Bytes,+ depth: usize+) void = trust {+ if walk.failed {+ return+ }+ if depth > 4096 {+ walk.failed = true+ return+ }+ val body_opt = state.read_body(walk.handles, tree_id, types.TREE)+ val body: mut bytes.Bytes = bytes.empty()+ match body_opt {+ some b => {+ body = b+ }+ none => {+ walk.failed = true+ return+ }+ }+ val decoded = tree.decode(body)+ val t: mut ref tree.Tree = none+ match decoded {+ ok x => {+ t = x+ }+ err _ => {+ files.free_buffer(body)+ walk.failed = true+ return+ }+ }+ for e in t.entries {+ if walk.failed {+ break+ }+ if !valid_checkout_name(e.name) {+ walk.failed = true+ break+ }+ val path: bytes.Bytes = join_bytes(prefix, e.name)+ if e.kind == tree.KIND_SUBTREE {+ @append(walk.dirs, path)+ walk_tree(walk, e.target, path, depth + 1)+ } elif e.kind == tree.KIND_FILE+ || e.kind == tree.KIND_EXECUTABLE+ || e.kind == tree.KIND_SYMLINK {+ add_task(walk, path, e.kind, e.target)+ } elif e.kind == tree.KIND_SUBMODULE {+ @append(walk.dirs, path)+ } else {+ files.free_buffer(path)+ walk.failed = true+ }+ }+ tree.free_tree(t)+ files.free_buffer(body)+}++fn parse_veins_hex(hex: bytes.Bytes) option[objid.Id] = trust {+ if hex.len != 64 {+ return none+ }+ val raw: ref u8 = @alloc(32) as ref u8+ val i: mut usize = 0+ for i < 32 {+ val hi_c: u8 = bytes.Bytes.at(hex, i * 2)+ val lo_c: u8 = bytes.Bytes.at(hex, i * 2 + 1)+ val hi: mut i32 = -1+ val lo: mut i32 = -1+ if hi_c >= 48 && hi_c <= 57 {+ hi = (hi_c - 48) as i32+ } elif hi_c >= 97 && hi_c <= 102 {+ hi = (hi_c - 87) as i32+ } elif hi_c >= 65 && hi_c <= 70 {+ hi = (hi_c - 55) as i32+ }+ if lo_c >= 48 && lo_c <= 57 {+ lo = (lo_c - 48) as i32+ } elif lo_c >= 97 && lo_c <= 102 {+ lo = (lo_c - 87) as i32+ } elif lo_c >= 65 && lo_c <= 70 {+ lo = (lo_c - 55) as i32+ }+ if hi < 0 || lo < 0 {+ @free(raw as ref void)+ return none+ }+ @store8(@ptradd(raw, i as i64), ((hi * 16 + lo) as u8))+ i+++ }+ return some objid.id(raw)+}++fn bookmark_target(v: ref view.View, name: bytes.Bytes) option[objid.Id] = trust {+ for bm in v.bookmarks {+ if bytes.Bytes.eql(bm.name, name) {+ if @len(bm.targets.adds) == 1 {+ val a = @get(bm.targets.adds, 0)+ if a is some id {+ return some id+ }+ }+ return none+ }+ }+ return none+}++fn tag_target(v: ref view.View, name: bytes.Bytes) option[objid.Id] = trust {+ for t in v.tags {+ if bytes.Bytes.eql(t.name, name) {+ return some t.target+ }+ }+ return none+}++fn working_copy_target(v: ref view.View) option[objid.Id] = trust {+ for w in v.working_copies {+ if bytes.Bytes.eql(w.workspace, bytes.bytes(c"default", 7)) {+ return some w.target+ }+ }+ return none+}++fn resolve_revision(v: ref view.View, rev: bytes.Bytes) option[objid.Id] = trust {+ if rev.len == 0 || bytes.Bytes.eql(rev, bytes.bytes(c"@", 1)) {+ return working_copy_target(v)+ }+ val bm = bookmark_target(v, rev)+ if bm is some id {+ return some id+ }+ val tg = tag_target(v, rev)+ if tg is some id2 {+ return some id2+ }+ return parse_veins_hex(rev)+}++/// Check out `rev` (empty means the working-copy commit) into the repository.+pub fn run(repo: layout.Repo, rev: bytes.Bytes) i32 = trust {+ val store_handle: mut store.Store = store.open_all(repo)+ val mut_view = state.current_view(repo, store_handle.handles)+ val v: mut ref view.View = none+ match mut_view {+ some x => {+ v = x+ }+ none => {+ msg.error_prefix()+ stdio.eprint("no operation state; import a repository first\n", {})+ store.close(store_handle)+ return 1+ }+ }+ val target_opt = resolve_revision(v, rev)+ val commit_id: mut objid.Id = objid.id_none()+ match target_opt {+ some id => {+ commit_id = id+ }+ none => {+ msg.error_prefix()+ stdio.eprint("unknown revision: {s}\n", {str.view(rev.ptr, rev.len as i64)})+ view.free_view(v)+ store.close(store_handle)+ return 1+ }+ }+ val cbody_opt = state.read_body(store_handle.handles, commit_id, types.COMMIT)+ val cbody: mut bytes.Bytes = bytes.empty()+ match cbody_opt {+ some b => {+ cbody = b+ }+ none => {+ msg.error_prefix()+ stdio.eprint("cannot read commit\n", {})+ view.free_view(v)+ store.close(store_handle)+ return 1+ }+ }+ val cdecoded = commit.decode(cbody)+ val c: mut ref commit.Commit = none+ match cdecoded {+ ok x => {+ c = x+ }+ err _ => {+ files.free_buffer(cbody)+ msg.error_prefix()+ stdio.eprint("corrupt commit\n", {})+ view.free_view(v)+ store.close(store_handle)+ return 1+ }+ }+ val root_tree: objid.Id = copy_id(c.root_tree)+ commit.free_commit(c)+ files.free_buffer(cbody)+ view.free_view(v)++ val root: str.StringView = layout.root_view(repo)+ val root_c: ref u8 = bytes.Bytes.to_cstr(bytes.from_cstr(root.ptr))+ val root_fd: i32 = openat(-100, root_c, o_directory() | o_cloexec(), 0)+ @free(root_c as ref void)+ if root_fd < 0 {+ msg.error_prefix()+ stdio.eprint("cannot open working directory\n", {})+ store.close(store_handle)+ return 1+ }++ val tasks: list[ref CheckoutTask] = lists.new[ref CheckoutTask]()+ val dirs: list[bytes.Bytes] = lists.new[bytes.Bytes]()+ val walk: mut CheckoutWalk = CheckoutWalk{+ handles: store_handle.handles,+ tasks: tasks,+ dirs: dirs,+ failed: false,+ error: bytes.empty()+ }+ walk_tree(walk, root_tree, bytes.empty(), 0)+ if walk.failed {+ msg.error_prefix()+ stdio.eprint("checkout tree validation failed\n", {})+ close(root_fd)+ store.close(store_handle)+ return 1+ }++ val dir_failed: mut bool = false+ for d in dirs {+ if !ensure_dir(root_fd, d) {+ dir_failed = true+ msg.error_prefix()+ stdio.eprint("cannot create directory: {s}\n", {str.view(d.ptr, d.len as i64)})+ break+ }+ }+ if dir_failed {+ close(root_fd)+ store.close(store_handle)+ return 1+ }++ val ac: allocators.HeapAllocator = @zeroed+ val git_path: str.StringView = layout.git_dir(repo)+ val git_opt = object.open(git_path)+ val git_repo: mut object.GitRepo = @zeroed+ val git_open: mut bool = false+ match git_opt {+ ok g => {+ git_repo = g+ git_open = true+ }+ err _ => {+ files.free_path(git_path)+ }+ }+ val git_lock_opt = thread.Mutex.new[allocators.HeapAllocator](ac)+ val git_lock: mut ref void = none+ val git_usable: mut bool = git_open+ match git_lock_opt {+ some m => {+ git_lock = m+ }+ none => {+ git_usable = false+ }+ }+ val count: usize = cpu_count()+ val n: usize = @len(tasks)+ val workers: mut usize = count+ if workers < 1 {+ workers = 1+ }+ if workers > n && n > 0 {+ workers = n+ }+ val thread_refs: mut list[ref void] = lists.new[ref void]()+ val jobs: mut list[ref CheckoutJob] = lists.new[ref CheckoutJob]()+ if n == 0 {+ workers = 0+ }+ val w: mut usize = 0+ for w < workers {+ val job: mut ref CheckoutJob = @alloc(@sizeof(CheckoutJob)) as ref CheckoutJob+ job.handles = store_handle.handles+ job.root_fd = root_fd+ job.tasks = tasks+ job.start = w+ job.step = workers+ job.failed = false+ job.error = bytes.empty()+ job.git = git_repo+ job.git_lock = git_lock+ job.has_git = git_usable+ @append(jobs, job)+ val tr = thread.Thread.new[allocators.HeapAllocator](ac, checkout_worker, job as ref void)+ match tr {+ ok t => {+ @append(thread_refs, t)+ }+ err _ => {+ job.failed = true+ job.error = bytes.Bytes.dup(bytes.from_cstr(c"cannot start checkout thread"))+ }+ }+ w+++ }++ val failed_path: mut bytes.Bytes = bytes.empty()+ val had_failure: mut bool = false+ val j: mut usize = 0+ for j < @len(jobs) {+ val job = @get(jobs, j)+ if job is some jb {+ val tr = @get(thread_refs, j)+ if tr is some t {+ val joined = thread.Thread.join[allocators.HeapAllocator](ac, t)+ match joined {+ ok _ => {+ }+ err _ => {+ }+ }+ }+ if jb.failed {+ had_failure = true+ if failed_path.len == 0 && jb.error.len > 0 {+ failed_path = jb.error+ }+ }+ }+ j+++ }++ if git_lock != none {+ thread.Mutex.free[allocators.HeapAllocator](ac, git_lock)+ }+ if git_open {+ object.free(git_repo)+ }+ close(root_fd)+ if had_failure {+ if failed_path.len > 0 {+ msg.error_prefix()+ stdio.eprint(+ "checkout failed at: {s}\n",+ {str.view(failed_path.ptr, failed_path.len as i64)}+ )+ } else {+ msg.error_prefix()+ stdio.eprint("checkout failed\n", {})+ }+ store.close(store_handle)+ return 1+ }++ msg.info_prefix()+ stdio.print("checked out {d} files\n", {n})+ store.close(store_handle)+ return 0+}--- /dev/null+++ b/veins/src/worktree/ignore.sx@@ -0,0 +1,307 @@+/// Gitignore-style ignore rules for working-copy snapshots.+///+/// Supports the subset of `.vnexclude` / `.gitignore` syntax that matters for+/// deciding which new files enter a snapshot: comments, negation, directory+/// patterns, anchored patterns, `*`, `?`, and `**`.++val str = use("std/string")+val bytes = use("../core/bytes.sx")+val lists = use("../core/lists.sx")+val files = use("../io/files.sx")++pub type Rule = {+ pattern: mut bytes.Bytes+ negated: mut bool+ dir_only: mut bool+ anchored: mut bool+ has_slash: mut bool+ base: mut bytes.Bytes+}++pub type Rules = {+ items: mut list[ref Rule]+}++fn new_rule(+ pattern: bytes.Bytes,+ negated: bool,+ dir_only: bool,+ anchored: bool,+ has_slash: bool,+ base: bytes.Bytes+) ref Rule = trust {+ val r: mut ref Rule = @alloc(@sizeof(Rule)) as ref Rule+ r.pattern = bytes.Bytes.dup(pattern)+ r.negated = negated+ r.dir_only = dir_only+ r.anchored = anchored+ r.has_slash = has_slash+ r.base = bytes.Bytes.dup(base)+ return r+}++pub fn empty() Rules = trust {+ return Rules{items: lists.new[ref Rule]()}+}++fn trim(b: bytes.Bytes) bytes.Bytes = trust {+ val start: mut usize = 0+ val end: mut usize = b.len+ for start < end {+ val c: u8 = bytes.Bytes.at(b, start)+ if c != 32 && c != 9 && c != 13 {+ break+ }+ start+++ }+ for end > start {+ val c2: u8 = bytes.Bytes.at(b, end - 1)+ if c2 != 32 && c2 != 9 && c2 != 13 {+ break+ }+ end--+ }+ return bytes.Bytes.slice(b, start, end)+}++fn add_line(rules: mut Rules, base: bytes.Bytes, line_in: bytes.Bytes) void = trust {+ val line: bytes.Bytes = trim(line_in)+ if line.len == 0 {+ return+ }+ if bytes.Bytes.at(line, 0) == 35 {+ return+ }+ val negated: mut bool = false+ val start: mut usize = 0+ if bytes.Bytes.at(line, 0) == 33 {+ negated = true+ start = 1+ }+ if start >= line.len {+ return+ }+ val mut_end: mut usize = line.len+ val dir_only: mut bool = false+ if bytes.Bytes.at(line, mut_end - 1) == 47 {+ dir_only = true+ mut_end--+ }+ if start >= mut_end {+ return+ }+ val anchored: mut bool = false+ if bytes.Bytes.at(line, start) == 47 {+ anchored = true+ start+++ }+ if start >= mut_end {+ return+ }+ val pattern: bytes.Bytes = bytes.Bytes.slice(line, start, mut_end)+ val has_slash: mut bool = false+ val i: mut usize = 0+ for i < pattern.len {+ if bytes.Bytes.at(pattern, i) == 47 {+ has_slash = true+ }+ i+++ }+ @append(+ rules.items,+ new_rule(pattern, negated, dir_only, anchored, has_slash, base)+ )+}++pub fn load_file(+ rules: mut Rules,+ repo_root: str.StringView,+ base: bytes.Bytes,+ name: str.StringView+) void = trust {+ val base_view: str.StringView = files.to_view(base)+ val dir: str.StringView = files.join(repo_root, base_view)+ val path: str.StringView = files.join(dir, name)+ val data_opt = files.read_all(path)+ files.free_path(dir)+ files.free_path(path)+ if data_opt is some data {+ val pos: mut usize = 0+ val line_start: mut usize = 0+ for pos <= data.len {+ val at_end: bool = pos == data.len+ if at_end || bytes.Bytes.at(data, pos) == 10 {+ add_line(rules, base, bytes.Bytes.slice(data, line_start, pos))+ line_start = pos + 1+ }+ pos+++ }+ files.free_buffer(data)+ }+}++/// Load root-level `.vnexclude` and `.gitignore`. Per-directory files are+/// added during traversal by `load_file`.+pub fn load_root(rules: mut Rules, repo_root: str.StringView) void = trust {+ load_file(rules, repo_root, bytes.empty(), str.from_cstr(c".vnexclude"))+ load_file(rules, repo_root, bytes.empty(), str.from_cstr(c".gitignore"))+}++fn glob_here(pattern: bytes.Bytes, pi: usize, text: bytes.Bytes, ti: usize) bool = trust {+ if pi >= pattern.len {+ return ti >= text.len+ }+ val pc: u8 = bytes.Bytes.at(pattern, pi)+ if pc == 42 {+ val double: bool = pi + 1 < pattern.len && bytes.Bytes.at(pattern, pi + 1) == 42+ if double {+ val next: usize = pi + 2+ if next < pattern.len && bytes.Bytes.at(pattern, next) == 47 {+ val after: usize = next + 1+ val j: mut usize = ti+ for {+ if glob_here(pattern, after, text, j) {+ return true+ }+ if j >= text.len {+ break+ }+ if bytes.Bytes.at(text, j) == 47 {+ j+++ continue+ }+ j+++ for j < text.len && bytes.Bytes.at(text, j) != 47 {+ j+++ }+ }+ return false+ }+ val j2: mut usize = ti+ for {+ if glob_here(pattern, next, text, j2) {+ return true+ }+ if j2 >= text.len {+ break+ }+ j2+++ }+ return false+ }+ val j3: mut usize = ti+ for {+ if glob_here(pattern, pi + 1, text, j3) {+ return true+ }+ if j3 >= text.len || bytes.Bytes.at(text, j3) == 47 {+ break+ }+ j3+++ }+ return false+ }+ if ti >= text.len {+ return false+ }+ if pc == 63 {+ if bytes.Bytes.at(text, ti) == 47 {+ return false+ }+ return glob_here(pattern, pi + 1, text, ti + 1)+ }+ if pc != bytes.Bytes.at(text, ti) {+ return false+ }+ return glob_here(pattern, pi + 1, text, ti + 1)+}++fn component_end(text: bytes.Bytes, start: usize) usize = trust {+ val i: mut usize = start+ for i < text.len && bytes.Bytes.at(text, i) != 47 {+ i+++ }+ return i+}++fn match_component(pattern: bytes.Bytes, text: bytes.Bytes) bool = trust {+ return glob_here(pattern, 0, text, 0)+}++fn relative_to(base: bytes.Bytes, path: bytes.Bytes) option[bytes.Bytes] = trust {+ if base.len == 0 {+ return some path+ }+ if path.len <= base.len {+ return none+ }+ val prefix: bytes.Bytes = bytes.Bytes.slice(path, 0, base.len)+ if !bytes.Bytes.eql(prefix, base) {+ return none+ }+ if bytes.Bytes.at(path, base.len) != 47 {+ return none+ }+ return some bytes.Bytes.slice(path, base.len + 1, path.len)+}++fn rule_matches(rule: ref Rule, path: bytes.Bytes, is_dir: bool) bool = trust {+ val rel_opt = relative_to(rule.base, path)+ val rel: mut bytes.Bytes = bytes.empty()+ match rel_opt {+ some r => {+ rel = r+ }+ none => {+ return false+ }+ }+ if rel.len == 0 {+ return false+ }+ if rule.dir_only && !is_dir {+ return false+ }+ if !rule.has_slash && !rule.anchored {+ val start: mut usize = 0+ for {+ val end: usize = component_end(rel, start)+ if match_component(rule.pattern, bytes.Bytes.slice(rel, start, end)) {+ return true+ }+ if end >= rel.len {+ break+ }+ start = end + 1+ }+ return false+ }+ return glob_here(rule.pattern, 0, rel, 0)+}++/// True when `path` is ignored. Later rules override earlier ones.+pub fn ignored(rules: Rules, path: bytes.Bytes, is_dir: bool) bool = trust {+ val ignored_flag: mut bool = false+ for r in rules.items {+ if rule_matches(r, path, is_dir) {+ ignored_flag = !r.negated+ }+ }+ return ignored_flag+}++pub fn free(rules: Rules) void = trust {+ for r in rules.items {+ if r.pattern.ptr != none {+ val pp: mut ref void = r.pattern.ptr as ref void+ @free(pp)+ }+ if r.base.ptr != none {+ val bp: mut ref void = r.base.ptr as ref void+ @free(bp)+ }+ val rp: mut ref void = r as ref void+ @free(rp)+ }+ @listfree(rules.items)+}--- /dev/null+++ b/veins/src/worktree/snapshot.sx@@ -0,0 +1,998 @@+/// Working-copy snapshotting.+///+/// Before a command reads or writes the working copy, veins snapshots the files+/// on disk into the working-copy commit. The commit keeps its change ID and+/// message and is amended in place. A snapshot that produces the same tree as+/// the existing commit does not create an operation.++val str = use("std/string")+val stdio = use("std/stdio")+val msg = use("../core/msg.sx")+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 random = use("std/crypto/random")+val objid = use("../object/id.sx")+val types = use("../object/types.sx")+val tree = use("../object/tree.sx")+val commit = use("../object/commit.sx")+val blob = use("../object/blob.sx")+val treewalk = use("../object/treewalk.sx")+val store = use("../store/store.sx")+val layout = use("../store/layout.sx")+val state = use("../store/state.sx")+val txn = use("../store/txn.sx")+val viewops = use("../store/viewops.sx")+val identity = use("../core/identity.sx")+val gitmap = use("../git/map.sx")+val view = use("../object/view.sx")+val files = use("../io/files.sx")+val native = use("../io/native.sx")+val stat = use("../io/stat.sx")+val raw = use("../object/raw.sx")+val ignore = use("ignore.sx")++type CacheEntry = {+ path: mut bytes.Bytes+ size: mut u64+ mtime_ns: mut u64+ inode: mut u64+ kind: mut u8+ executable: mut bool+ target: mut objid.Id+}++type Cache = {+ entries: mut list[ref CacheEntry]+ written_ms: mut i64+}++fn copy_id(id: objid.Id) objid.Id = trust {+ val out: ref u8 = @alloc(32) as ref u8+ @memcpy(out as ref void, id.ptr as ref void, 32)+ return objid.id(out)+}++fn join_path(prefix: bytes.Bytes, name: bytes.Bytes) bytes.Bytes = trust {+ if prefix.len == 0 {+ return bytes.Bytes.dup(name)+ }+ val out: ref u8 = @alloc(prefix.len + 1 + name.len) as ref u8+ @memcpy(out as ref void, prefix.ptr as ref void, prefix.len)+ @store8(@ptradd(out, prefix.len as i64), 47)+ @memcpy(+ @ptradd(out, (prefix.len + 1) as i64) as ref void,+ name.ptr as ref void,+ name.len+ )+ return bytes.bytes(out, prefix.len + 1 + name.len)+}++fn new_entry(+ path: bytes.Bytes,+ info: stat.StatInfo,+ executable: bool,+ target: objid.Id+) ref CacheEntry = trust {+ val e: mut ref CacheEntry = @alloc(@sizeof(CacheEntry)) as ref CacheEntry+ e.path = path+ e.size = info.size+ e.mtime_ns = info.mtime_ns+ e.inode = info.inode+ e.kind = info.kind+ e.executable = executable+ e.target = copy_id(target)+ return e+}++fn free_entry(e: ref CacheEntry) void = trust {+ if e.path.ptr != none {+ val pp: mut ref void = e.path.ptr as ref void+ @free(pp)+ }+ if e.target.ptr != none {+ val tp: mut ref void = e.target.ptr as ref void+ @free(tp)+ }+ val ep: mut ref void = e as ref void+ @free(ep)+}++fn free_cache(c: Cache) void = trust {+ for e in c.entries {+ free_entry(e)+ }+ @listfree(c.entries)+}++fn entry_at(xs: list[ref CacheEntry], i: usize) ref CacheEntry = trust {+ val o = @get(xs, i)+ if o is some e {+ return e+ }+ assert false+ return none+}++fn sort_cache(xs: mut list[ref CacheEntry]) void = trust {+ val n: usize = @len(xs)+ val i: mut usize = 1+ for i < n {+ val cur = @get(xs, i)+ val c: mut ref CacheEntry = none+ if cur is some v {+ c = v+ }+ val j: mut usize = i+ for j > 0 {+ val prev_opt = @get(xs, j - 1)+ val prev: mut ref CacheEntry = none+ if prev_opt is some v2 {+ prev = v2+ }+ if bytes.Bytes.cmp(prev.path, c.path) <= 0 {+ break+ }+ @set(xs, j, prev)+ j--+ }+ @set(xs, j, c)+ i+++ }+}++fn cache_lookup(c: Cache, path: bytes.Bytes) option[ref CacheEntry] = trust {+ val lo: mut usize = 0+ val hi: mut usize = @len(c.entries)+ for lo < hi {+ val mid: usize = lo + (hi - lo) / 2+ val e: ref CacheEntry = entry_at(c.entries, mid)+ val cmp: i64 = bytes.Bytes.cmp(e.path, path)+ if cmp == 0 {+ return some e+ }+ if cmp < 0 {+ lo = mid + 1+ } else {+ hi = mid+ }+ }+ return none+}++fn cache_u8(r: mut reader.Reader) option[u8] = trust {+ val x = reader.Reader.read_u8(r)+ match x {+ ok v => {+ return some(v)+ }+ err _ => {+ return none+ }+ }+}++fn cache_u64(r: mut reader.Reader) option[u64] = trust {+ val x = reader.Reader.read_u64_le(r)+ match x {+ ok v => {+ return some(v)+ }+ err _ => {+ return none+ }+ }+}++fn cache_varint(r: mut reader.Reader) option[u64] = trust {+ val x = reader.Reader.read_varint(r)+ match x {+ ok v => {+ return some(v)+ }+ err _ => {+ return none+ }+ }+}++fn cache_bytes(r: mut reader.Reader, max: usize) option[bytes.Bytes] = trust {+ val x = reader.Reader.read_bytes(r, max)+ match x {+ ok v => {+ return some(v)+ }+ err _ => {+ return none+ }+ }+}++fn cache_id(r: mut reader.Reader) option[ref u8] = trust {+ val x = reader.Reader.read_id(r)+ match x {+ ok v => {+ return some(v)+ }+ err _ => {+ return none+ }+ }+}++fn load_cache(repo: layout.Repo) Cache = trust {+ val c: mut Cache = Cache{entries: lists.new[ref CacheEntry](), written_ms: 0}+ val dir: str.StringView = layout.working_copy_dir(repo)+ val path: str.StringView = files.join(dir, str.from_cstr(c"stat-cache"))+ files.free_path(dir)+ val data_opt = files.read_all(path)+ files.free_path(path)+ val data: mut bytes.Bytes = bytes.empty()+ match data_opt {+ some d => {+ data = d+ }+ none => {+ return c+ }+ }+ if data.len < 13 || !bytes.Bytes.eql(bytes.Bytes.slice(data, 0, 4), bytes.bytes(c"VST1", 4)) {+ files.free_buffer(data)+ return c+ }+ val r: mut reader.Reader = reader.new(data.ptr, data.len)+ val version_opt = cache_u8(r)+ val version: mut u8 = 0+ match version_opt {+ some v => {+ version = v+ }+ none => {+ files.free_buffer(data)+ return c+ }+ }+ if version != 49 {+ files.free_buffer(data)+ return c+ }+ val written_opt = cache_u64(r)+ match written_opt {+ some written => {+ c.written_ms = written as i64+ }+ none => {+ files.free_buffer(data)+ return c+ }+ }+ val count_opt = cache_varint(r)+ val count: mut usize = 0+ match count_opt {+ some v => {+ count = v as usize+ }+ none => {+ files.free_buffer(data)+ return c+ }+ }+ val i: mut usize = 0+ for i < count {+ val p_opt = cache_bytes(r, 65536)+ val p: mut bytes.Bytes = bytes.empty()+ match p_opt {+ some v => {+ p = v+ }+ none => {+ break+ }+ }+ val sz_o = cache_u64(r)+ val mt_o = cache_u64(r)+ val ino_o = cache_u64(r)+ val kind_o = cache_u8(r)+ val ex_o = cache_u8(r)+ val idp_o = cache_id(r)+ if sz_o is none {+ break+ }+ if mt_o is none {+ break+ }+ if ino_o is none {+ break+ }+ if kind_o is none {+ break+ }+ if ex_o is none {+ break+ }+ if idp_o is none {+ break+ }+ val sz: mut u64 = 0+ val mt: mut u64 = 0+ val ino: mut u64 = 0+ val kind: mut u8 = 0+ val ex: mut u8 = 0+ val idp: mut ref u8 = none+ if sz_o is some v {+ sz = v+ }+ if mt_o is some v {+ mt = v+ }+ if ino_o is some v {+ ino = v+ }+ if kind_o is some v {+ kind = v+ }+ if ex_o is some v {+ ex = v+ }+ if idp_o is some v {+ idp = v+ }+ val e: mut ref CacheEntry = @alloc(@sizeof(CacheEntry)) as ref CacheEntry+ e.path = bytes.Bytes.dup(p)+ e.size = sz+ e.mtime_ns = mt+ e.inode = ino+ e.kind = kind+ e.executable = ex != 0+ e.target = copy_id(objid.id(idp))+ @append(c.entries, e)+ i+++ }+ files.free_buffer(data)+ sort_cache(c.entries)+ return c+}++fn save_cache(repo: layout.Repo, c: Cache) bool = trust {+ val b: mut buf.Buf = buf.new(4096)+ buf.Buf.put_raw(b, c"VST1", 4)+ buf.Buf.put_u8(b, 49)+ buf.Buf.put_u64_le(b, time.unix_now_millis() as u64)+ buf.Buf.put_varint(b, @len(c.entries) as u64)+ for e in c.entries {+ buf.Buf.put_length_prefixed(b, e.path)+ buf.Buf.put_u64_le(b, e.size)+ buf.Buf.put_u64_le(b, e.mtime_ns)+ buf.Buf.put_u64_le(b, e.inode)+ buf.Buf.put_u8(b, e.kind)+ val ex: mut u8 = 0+ if e.executable {+ ex = 1+ }+ buf.Buf.put_u8(b, ex)+ buf.Buf.put_id(b, e.target.ptr)+ }+ val dir: str.StringView = layout.working_copy_dir(repo)+ val final: str.StringView = files.join(dir, str.from_cstr(c"stat-cache"))+ val tmpd: str.StringView = layout.tmp_dir(repo)+ val tmp: str.StringView = files.join(tmpd, str.from_cstr(c"stat-cache.tmp"))+ val wrote: bool = native.write_atomic(tmp, final, tmpd, dir, buf.Buf.view(b))+ files.free_path(dir)+ files.free_path(final)+ files.free_path(tmpd)+ files.free_path(tmp)+ buf.Buf.free(b)+ return wrote+}++fn add_blob_data(tx: mut ref txn.Txn, data: ref u8, len: usize) objid.Id = trust {+ val built: ref blob.BlobBuild = blob.build(data, len)+ val id: objid.Id = copy_id(blob.root_id(built))+ val ri: mut usize = 0+ for ri < @len(built.objects) {+ val ro = @get(built.objects, ri)+ if ro is some obj {+ val orf: mut ref raw.RawObject = obj+ val oid: objid.Id = objid.id(orf.id)+ val _ = txn.add_known(tx, orf.type_byte, oid, orf.body)+ orf.body = bytes.empty()+ }+ ri+++ }+ blob.free_build(built)+ return id+}++fn cache_matches(+ e: ref CacheEntry,+ info: stat.StatInfo,+ executable: bool,+ now_ms: i64,+ written_ms: i64+) bool = trust {+ if e.size != info.size || e.mtime_ns != info.mtime_ns || e.inode != info.inode {+ return false+ }+ if e.executable != executable || e.kind != info.kind {+ return false+ }+ // Files touched inside the racy window are re-verified by content.+ val now_ns: i64 = now_ms * 1000000+ val written_ns: i64 = written_ms * 1000000+ val window: i64 = 2000000000+ if info.mtime_ns as i64 >= written_ns - window {+ return false+ }+ if now_ns - (info.mtime_ns as i64) < window {+ return false+ }+ return true+}++fn sort_names(xs: mut list[ref u8]) void = trust {+ val n: usize = @len(xs)+ val i: mut usize = 1+ for i < n {+ val cur = @get(xs, i)+ val c: mut ref u8 = none+ if cur is some v {+ c = v+ }+ val j: mut usize = i+ for j > 0 {+ val prev_opt = @get(xs, j - 1)+ val prev: mut ref u8 = none+ if prev_opt is some v2 {+ prev = v2+ }+ val cmp: i64 = bytes.Bytes.cmp(bytes.from_cstr(prev), bytes.from_cstr(c))+ if cmp <= 0 {+ break+ }+ @set(xs, j, prev)+ j--+ }+ @set(xs, j, c)+ i+++ }+}++fn is_meta_name(name: bytes.Bytes) bool = trust {+ if bytes.Bytes.eql(name, bytes.bytes(c".veins", 6)) {+ return true+ }+ if bytes.Bytes.eql(name, bytes.bytes(c".git", 4)) {+ return true+ }+ return false+}++fn free_local(local: ignore.Rules, keep: usize) void = trust {+ val i: mut usize = keep+ for i < @len(local.items) {+ val o = @get(local.items, i)+ if o is some r {+ if r.pattern.ptr != none {+ val pp: mut ref void = r.pattern.ptr as ref void+ @free(pp)+ }+ if r.base.ptr != none {+ val bp: mut ref void = r.base.ptr as ref void+ @free(bp)+ }+ val rp: mut ref void = r as ref void+ @free(rp)+ }+ i+++ }+ @listfree(local.items)+}++fn build_dir(+ tx: mut ref txn.Txn,+ root: str.StringView,+ handles: list[ref store.Handle],+ rel: bytes.Bytes,+ old_tree: option[objid.Id],+ base_rules: ignore.Rules,+ cache: Cache,+ new_cache: mut list[ref CacheEntry],+ now_ms: i64+) option[objid.Id] = trust {+ val local: mut ignore.Rules = ignore.empty()+ for r in base_rules.items {+ @append(local.items, r)+ }+ val keep: usize = @len(local.items)+ ignore.load_file(local, root, rel, str.from_cstr(c".vnexclude"))+ ignore.load_file(local, root, rel, str.from_cstr(c".gitignore"))++ val old: mut ref tree.Tree = none+ val have_old: mut bool = false+ if old_tree is some oid {+ val t_opt = treewalk.read_tree(handles, oid)+ match t_opt {+ some t => {+ old = t+ have_old = true+ }+ none => {+ free_local(local, keep)+ return none+ }+ }+ }++ val rel_view: str.StringView = files.to_view(rel)+ val dir: str.StringView = files.join(root, rel_view)+ if !files.exists_dir(dir) {+ files.free_path(dir)+ if have_old {+ tree.free_tree(old)+ }+ free_local(local, keep)+ return none+ }+ val names_list: mut list[ref u8] = files.list_dir(dir)+ sort_names(names_list)++ val entries: mut list[ref tree.TreeEntry] = lists.new[ref tree.TreeEntry]()+ val failed: mut bool = false+ for name_c in names_list {+ if failed {+ break+ }+ val name: bytes.Bytes = bytes.from_cstr(name_c)+ if is_meta_name(name) {+ continue+ }+ val path: bytes.Bytes = join_path(rel, name)+ val fs_path: str.StringView = files.join(dir, str.from_cstr(name_c))+ val stat_opt = stat.read(fs_path)+ files.free_path(fs_path)+ if stat_opt is none {+ files.free_buffer(path)+ continue+ }+ val info: mut stat.StatInfo = stat.StatInfo{+ kind: 0,+ executable: false,+ size: 0,+ mtime_ns: 0,+ inode: 0+ }+ match stat_opt {+ some si => {+ info = si+ }+ none => {+ files.free_buffer(path)+ continue+ }+ }+ if info.kind == stat.KIND_MISSING {+ files.free_buffer(path)+ continue+ }+ val is_dir: bool = info.kind == stat.KIND_DIR+ val ignored: bool = ignore.ignored(local, path, is_dir)+ val old_idx: mut i32 = -1+ if have_old {+ old_idx = treewalk.find_name(old, name)+ }+ if ignored && old_idx < 0 {+ files.free_buffer(path)+ continue+ }+ if is_dir {+ val child_old: mut option[objid.Id] = none+ if have_old && old_idx >= 0 {+ val oe = @get(old.entries, old_idx as usize)+ if oe is some e {+ if e.kind == tree.KIND_SUBTREE {+ child_old = some copy_id(e.target)+ }+ }+ }+ val child_opt = build_dir(+ tx,+ root,+ handles,+ path,+ child_old,+ local,+ cache,+ new_cache,+ now_ms+ )+ if child_old is some co {+ if co.ptr != none {+ val cp: mut ref void = co.ptr as ref void+ @free(cp)+ }+ }+ if child_opt is some cid {+ @append(entries, tree.entry(bytes.Bytes.dup(name), tree.KIND_SUBTREE, cid))+ }+ files.free_buffer(path)+ } elif info.kind == stat.KIND_LINK {+ val fs2: str.StringView = files.join(dir, str.from_cstr(name_c))+ val target_opt = stat.link_target(fs2)+ files.free_path(fs2)+ if target_opt is some target {+ val bid: objid.Id = add_blob_data(tx, target.ptr, target.len)+ val kind: u8 = tree.KIND_SYMLINK+ @append(entries, tree.entry(bytes.Bytes.dup(name), kind, bid))+ @append(new_cache, new_entry(bytes.Bytes.dup(path), info, false, bid))+ files.free_buffer(target)+ }+ files.free_buffer(path)+ } else {+ val executable: bool = info.executable+ val cached = cache_lookup(cache, path)+ val reuse: mut bool = false+ val target: mut objid.Id = objid.id_none()+ if cached is some ce {+ if cache_matches(ce, info, executable, now_ms, cache.written_ms) {+ target = copy_id(ce.target)+ reuse = true+ }+ }+ if !reuse {+ val fs3: str.StringView = files.join(dir, str.from_cstr(name_c))+ val data_opt = files.read_all(fs3)+ files.free_path(fs3)+ match data_opt {+ some data => {+ target = add_blob_data(tx, data.ptr, data.len)+ files.free_buffer(data)+ }+ none => {+ failed = true+ }+ }+ }+ if !failed {+ @append(new_cache, new_entry(bytes.Bytes.dup(path), info, executable, target))+ val kind: mut u8 = tree.KIND_FILE+ if executable {+ kind = tree.KIND_EXECUTABLE+ }+ @append(entries, tree.entry(bytes.Bytes.dup(name), kind, target))+ }+ files.free_buffer(path)+ }+ }+ files.free_names(names_list)+ files.free_path(dir)++ val out: mut option[objid.Id] = none+ if !failed {+ if @len(entries) > 0 {+ val encoded = tree.encode(entries)+ match encoded {+ ok body => {+ val id: objid.Id = txn.add_object(tx, types.TREE, body)+ out = some(copy_id(id))+ if id.ptr != none {+ val ip: mut ref void = id.ptr as ref void+ @free(ip)+ }+ }+ err _ => {+ failed = true+ }+ }+ }+ }+ for e in entries {+ if e.name.ptr != none {+ val np: mut ref void = e.name.ptr as ref void+ @free(np)+ }+ if e.target.ptr != none {+ val tp2: mut ref void = e.target.ptr as ref void+ @free(tp2)+ }+ val ep: mut ref void = e as ref void+ @free(ep)+ }+ @listfree(entries)+ if have_old {+ tree.free_tree(old)+ }+ free_local(local, keep)+ if failed {+ return none+ }+ return out+}++fn empty_tree_id(tx: mut ref txn.Txn) objid.Id = trust {+ val t: tree.Tree = tree.empty()+ val encoded = tree.encode(t.entries)+ val body: mut bytes.Bytes = bytes.empty()+ match encoded {+ ok b => {+ body = b+ }+ err _ => {+ return objid.id(none)+ }+ }+ val id: objid.Id = txn.add_object(tx, types.TREE, body)+ @listfree(t.entries)+ return id+}++fn remove_wc_head(v: mut ref view.View, id: objid.Id) void = trust {+ viewops.remove_head(v, id)+}++/// Snapshot the working tree into `@`. Returns 0 on success.+pub fn run(repo: layout.Repo) i32 = trust {+ val tx_opt = txn.begin(repo)+ val tx: mut ref txn.Txn = none+ match tx_opt {+ some t => {+ tx = t+ }+ none => {+ msg.error_prefix()+ stdio.eprint("cannot load repository state\n", {})+ return 1+ }+ }++ val st: store.Store = store.open_all(repo)+ val wc_opt = viewops.working_copy(tx.view)+ val wc: mut objid.Id = objid.id_none()+ val have_wc: mut bool = false+ if wc_opt is some id {+ wc = id+ have_wc = true+ }++ val cbody: mut bytes.Bytes = bytes.empty()+ val c: mut ref commit.Commit = none+ val old_tree: mut option[objid.Id] = none+ if have_wc {+ val body_opt = state.read_body(st.handles, wc, types.COMMIT)+ match body_opt {+ some b => {+ cbody = b+ val decoded = commit.decode(cbody)+ match decoded {+ ok x => {+ c = x+ old_tree = some(copy_id(c.root_tree))+ }+ err _ => {+ msg.error_prefix()+ stdio.eprint("corrupt working-copy commit\n", {})+ store.close(st)+ txn.abort(tx)+ if wc.ptr != none {+ val wp: mut ref void = wc.ptr as ref void+ @free(wp)+ }+ return 1+ }+ }+ }+ none => {+ msg.error_prefix()+ stdio.eprint("missing working-copy commit\n", {})+ store.close(st)+ txn.abort(tx)+ if wc.ptr != none {+ val wp2: mut ref void = wc.ptr as ref void+ @free(wp2)+ }+ return 1+ }+ }+ }++ val root: str.StringView = layout.root_view(repo)+ val rules: mut ignore.Rules = ignore.empty()+ ignore.load_root(rules, root)+ val cache: Cache = load_cache(repo)+ val new_cache: mut list[ref CacheEntry] = lists.new[ref CacheEntry]()+ val now_ms: i64 = time.unix_now_millis()+ val built = build_dir(+ tx,+ root,+ st.handles,+ bytes.empty(),+ old_tree,+ rules,+ cache,+ new_cache,+ now_ms+ )+ val new_root: mut objid.Id = objid.id_none()+ val build_failed: mut bool = false+ match built {+ some id => {+ new_root = id+ }+ none => {+ if @len(new_cache) > 0 {+ // Files were produced before a failure; treat as an error.+ build_failed = true+ } else {+ new_root = empty_tree_id(tx)+ }+ }+ }+ if objid.Id.is_none(new_root) && !build_failed {+ msg.error_prefix()+ stdio.eprint("failed to build working-copy tree\n", {})+ build_failed = true+ }+ if build_failed {+ store.close(st)+ txn.abort(tx)+ if c != none {+ commit.free_commit(c)+ }+ if cbody.ptr != none {+ files.free_buffer(cbody)+ }+ if old_tree is some ot {+ if ot.ptr != none {+ val op: mut ref void = ot.ptr as ref void+ @free(op)+ }+ }+ if wc.ptr != none {+ val wp3: mut ref void = wc.ptr as ref void+ @free(wp3)+ }+ ignore.free(rules)+ free_cache(cache)+ for e in new_cache {+ free_entry(e)+ }+ @listfree(new_cache)+ return 1+ }++ val unchanged: mut bool = false+ if old_tree is some ot2 {+ if objid.Id.eql(ot2, new_root) {+ unchanged = true+ }+ }++ if unchanged {+ store.close(st)+ txn.abort(tx)+ if c != none {+ commit.free_commit(c)+ }+ if cbody.ptr != none {+ files.free_buffer(cbody)+ }+ if old_tree is some ot3 {+ if ot3.ptr != none {+ val op2: mut ref void = ot3.ptr as ref void+ @free(op2)+ }+ }+ if wc.ptr != none {+ val wp4: mut ref void = wc.ptr as ref void+ @free(wp4)+ }+ if new_root.ptr != none {+ val np2: mut ref void = new_root.ptr as ref void+ @free(np2)+ }+ ignore.free(rules)+ val sorted: mut Cache = Cache{entries: new_cache, written_ms: now_ms}+ sort_cache(sorted.entries)+ val _ = save_cache(repo, sorted)+ free_cache(cache)+ for e in new_cache {+ free_entry(e)+ }+ @listfree(new_cache)+ return 0+ }++ val committer: prim.Sig = identity.signature(repo)+ val author: mut prim.Sig = committer+ val parents: mut list[objid.Id] = lists.new[objid.Id]()+ val change_id: mut objid.ChangeId = objid.change_id(none)+ val message: mut bytes.Bytes = bytes.empty()+ if c != none {+ author = c.author+ for p in c.parents {+ @append(parents, copy_id(p))+ }+ change_id = c.change_id+ message = c.message+ } else {+ val cid: ref u8 = @alloc(16) as ref u8+ random.random_bytes(cid as ref void, 16)+ change_id = objid.change_id(cid)+ }+ val renames: list[ref commit.Rename] = lists.new[ref commit.Rename]()+ val extra: list[ref prim.KeyValue] = lists.new[ref prim.KeyValue]()+ val nc: mut ref commit.Commit = @alloc(@sizeof(commit.Commit)) as ref commit.Commit+ nc.version = 1+ nc.parents = parents+ nc.root_tree = new_root+ nc.change_id = change_id+ nc.author = author+ nc.committer = committer+ nc.message = message+ nc.renames_state = commit.RENAMES_RECORDED+ nc.renames = renames+ nc.extra = extra+ val encoded: bytes.Bytes = commit.encode(nc)+ val new_commit: objid.Id = txn.add_object(tx, types.COMMIT, encoded)+ @listfree(nc.parents)+ @listfree(nc.renames)+ @listfree(nc.extra)+ @free(nc as ref void)++ if have_wc {+ remove_wc_head(tx.view, wc)+ }+ viewops.set_workspace(tx.view, new_commit)+ viewops.rebuild_heads(tx.view)++ val status: i32 = txn.finish(tx, bytes.bytes(c"snapshot", 8))+ if status == 0 {+ val _ = gitmap.mark_native(repo, new_commit)+ }+ store.close(st)+ if c != none {+ commit.free_commit(c)+ }+ if cbody.ptr != none {+ files.free_buffer(cbody)+ }+ if old_tree is some ot4 {+ if ot4.ptr != none {+ val op3: mut ref void = ot4.ptr as ref void+ @free(op3)+ }+ }+ if wc.ptr != none {+ val wp5: mut ref void = wc.ptr as ref void+ @free(wp5)+ }+ if new_root.ptr != none {+ val np3: mut ref void = new_root.ptr as ref void+ @free(np3)+ }+ if new_commit.ptr != none {+ val cp2: mut ref void = new_commit.ptr as ref void+ @free(cp2)+ }+ identity.free_sig(committer)+ // Author/message/change ID fields borrowed from the old commit body (freed+ // above) or the freshly allocated random ID.+ if c == none && change_id.ptr != none {+ val cip: mut ref void = change_id.ptr as ref void+ @free(cip)+ }+ ignore.free(rules)+ if status == 0 {+ val sorted2: mut Cache = Cache{entries: new_cache, written_ms: now_ms}+ sort_cache(sorted2.entries)+ val _ = save_cache(repo, sorted2)+ }+ free_cache(cache)+ for e in new_cache {+ free_entry(e)+ }+ @listfree(new_cache)+ return status+}--- /dev/null+++ b/veins/sx.lock@@ -0,0 +1,1 @@+version "1"--- /dev/null+++ b/veins/sx.mod@@ -0,0 +1,20 @@+entry "./src/main.sx"+version "v0.0.1"+spectre_version "v0.0.18"++build release {+ action "mkdir -p $OUT && ./build-native.sh $OUT && spectre ./src/main.sx -release -link-obj:$OUT/veins_native.o -o ./vn"+ flags "-release"+ output "./vn"+ windows {+ output "vn.exe"+ }+}++build dev {+ action "mkdir -p $OUT && ./build-native.sh $OUT && spectre ./src/main.sx -link-obj:$OUT/veins_native.o -o ./vn-dev"+ output "./vn-dev"+ windows {+ output "vn-dev.exe"+ }+}