navid/veins / commit
96f30f16c431
Navid M <navidmomtahen@gmail.com> · 2026-11-28
parents: a437e0157beb
Browse files at this commit · Download source
--- a/veins/.gitignore+++ /dev/null@@ -1,12 +0,0 @@-cpp-prototype-*.dSYM-*.DS_Store-vn-dev-vn-veins-dev-SPECTRE_LANGUAGE_REFERENCE.md-lib/-std__*-s-out/-docs-out*/-.sxb/--- a/veins/build-native.sh+++ /dev/null@@ -1,159 +0,0 @@-#!/bin/sh-# Build the native hot-path objects and combine them for spectre -link-obj.-set -e--out="${1:-.sxb/native}"-arch_arg="${2:-auto}"-cc="${CC:-cc}"-mkdir -p "$out"--crypto="src/crypto"-b3="$crypto/blake3"--# Locate OpenSSL. Homebrew installs it keg-only on macOS, so neither the-# headers nor the static archives are in the default compiler search paths.-# An explicit OPENSSL_PREFIX always wins; otherwise ask brew/pkg-config.-openssl_prefix="${OPENSSL_PREFIX:-}"-if [ -z "$openssl_prefix" ] && [ "$(uname -s)" = "Darwin" ] &&- command -v brew >/dev/null 2>&1; then- for formula in openssl@3 openssl; do- candidate=$(brew --prefix "$formula" 2>/dev/null || true)- if [ -n "$candidate" ] && [ -d "$candidate/include/openssl" ]; then- openssl_prefix=$candidate- break- fi- done-fi-if [ -z "$openssl_prefix" ] && command -v pkg-config >/dev/null 2>&1; then- candidate=$(pkg-config --variable=prefix openssl 2>/dev/null || true)- if [ -n "$candidate" ] && [ -d "$candidate/include/openssl" ]; then- openssl_prefix=$candidate- fi-fi-openssl_cflags=""-if [ -n "$openssl_prefix" ] && [ -d "$openssl_prefix/include" ]; then- openssl_cflags="-I$openssl_prefix/include"-fi--# sx.mod passes the target architecture; fall back to the compiler's target so-# the script also works standalone.-target="$arch_arg"-if [ "$target" = "auto" ] || [ -z "$target" ]; then- target="${TARGET:-$("$cc" -dumpmachine 2>/dev/null || uname -m)}"-fi-case "$target" in- arm64*|aarch64*) arch=arm64 ;;- x86_64*|amd64*) arch=x86_64 ;;- i?86*) arch=x86 ;;- *) arch=unknown ;;-esac--"$cc" -O3 -c "$crypto/blake3_c.c" -o "$out/blake3_c.o"-# shellcheck disable=SC2086-"$cc" -O3 $openssl_cflags -c "$crypto/openssl_c.c" -o "$out/openssl_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"--objects="- $out/blake3_c.o- $out/blake3_impl.o- $out/blake3_dispatch.o- $out/blake3_portable.o-"--# Link the OpenSSL static libraries into the native object so that the final-# link does not depend on library ordering.-#-# Debian/Ubuntu build libcrypto.a with the JITTER entropy source enabled, so-# the archive contains undefined jent_* references. Spectre emits link flags-# before the native object, which means a plain `link "-ljitterentropy"` in the-# source is searched too early (and is dropped under --as-needed). Embed the-# jitter archive into the relocatable object instead, where ordering no longer-# matters.-ssl_a=""-crypto_a=""-if [ -n "$openssl_prefix" ]; then- if [ -f "$openssl_prefix/lib/libssl.a" ]; then- ssl_a="$openssl_prefix/lib/libssl.a"- fi- if [ -f "$openssl_prefix/lib/libcrypto.a" ]; then- crypto_a="$openssl_prefix/lib/libcrypto.a"- fi-fi-if [ -z "$ssl_a" ]; then- ssl_a=$("$cc" -print-file-name=libssl.a)-fi-if [ -z "$crypto_a" ]; then- crypto_a=$("$cc" -print-file-name=libcrypto.a)-fi-jit_a=$("$cc" -print-file-name=libjitterentropy.a)-if [ ! -f "$jit_a" ]; then- for cand in /usr/lib/*/libjitterentropy.a /usr/lib/libjitterentropy.a \- /usr/local/lib/libjitterentropy.a \- /usr/local/lib/*/libjitterentropy.a; do- if [ -f "$cand" ]; then- jit_a=$cand- break- fi- done-fi-if [ -f "$ssl_a" ] && [ -f "$crypto_a" ]; then- if [ "$(uname -s)" = "Darwin" ]; then- # ld64 has no --start-group/--whole-archive. A plain relocatable link- # pulls only the archive members needed by openssl_c.o, which keeps the- # binary independent of the keg-only Homebrew dylibs.- "$cc" -r "$out/openssl_c.o" "$ssl_a" "$crypto_a" \- -o "$out/openssl_embed.o"- else- # GNU ld: resolve the OpenSSL archive dependencies in one group. This- # pulls only referenced members instead of every object in libcrypto.a.- if [ -f "$jit_a" ]; then- "$cc" -r "$out/openssl_c.o" -Wl,--start-group \- "$ssl_a" "$crypto_a" "$jit_a" -Wl,--end-group \- -o "$out/openssl_embed.o"- else- "$cc" -r "$out/openssl_c.o" -Wl,--start-group \- "$ssl_a" "$crypto_a" -Wl,--end-group \- -o "$out/openssl_embed.o"- fi- if command -v nm >/dev/null 2>&1 &&- nm -u "$out/openssl_embed.o" 2>/dev/null | grep -q 'jent_'; then- echo "build-native.sh: libcrypto.a needs libjitterentropy; install libjitterentropy3-dev (Debian/Ubuntu) or libjitterentropy-devel (Fedora)" >&2- exit 1- fi- fi- objects="$objects $out/openssl_embed.o"-else- echo "build-native.sh: OpenSSL static libraries not found under ${openssl_prefix:-the compiler search path}; TLS will fail to link" >&2- objects="$objects $out/openssl_c.o"-fi--case "$arch" in- arm64)- # NEON is mandatory on AArch64, so no extra flags are needed.- "$cc" -O3 -c "$b3/blake3_neon.c" -o "$out/blake3_neon.o"- objects="$objects $out/blake3_neon.o"- ;;- x86_64|x86)- "$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"- objects="$objects- $out/blake3_sse2.o- $out/blake3_sse41.o- $out/blake3_avx2.o- $out/blake3_avx512.o- "- ;;- *)- echo "build-native.sh: unknown target '$target'; building portable BLAKE3 only" >&2- ;;-esac--"$cc" -O3 -c "src/chunking/fastcdc_c.c" -o "$out/fastcdc_c.o"-objects="$objects $out/fastcdc_c.o"--# shellcheck disable=SC2086-"$cc" -r $objects -o "$out/veins_native.o"--- a/veins/src/auth/access.sx+++ /dev/null@@ -1,356 +0,0 @@-/// Server-side `.veins/access` policy parsing and management.--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")-val layout = use("../store/layout.sx")-val ed = use("../crypto/ed25519.sx")-val tls = use("../crypto/tls.sx")--pub val ROLE_ANONYMOUS: u8 = 0-pub val ROLE_READ: u8 = 1-pub val ROLE_WRITE: u8 = 2--pub type AccessEntry = {- public_key: mut bytes.Bytes- name: mut bytes.Bytes- role: mut u64-}--pub type Access = {- valid: mut bool- error_line: mut i64- anonymous_read: mut bool- entries: mut list[ref AccessEntry]-}--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 tokenize(line: bytes.Bytes) list[bytes.Bytes] = trust {- val out: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()- val start: mut usize = 0- val i: mut usize = 0- for i <= line.len {- val at_end: bool = i == line.len- if at_end || bytes.Bytes.at(line, i) == 32 || bytes.Bytes.at(line, i) == 9 {- if i > start {- @append(out, bytes.Bytes.slice(line, start, i))- }- start = i + 1- }- i++- }- return out-}--fn token(toks: list[bytes.Bytes], i: usize) bytes.Bytes = trust {- val o = @get(toks, i)- if o is some v {- return v- }- return bytes.empty()-}--pub fn path(repo: layout.Repo) str.StringView = {- return files.join(layout.veins_dir(repo), str.from_cstr(c"access"))-}--fn free_entries(es: list[ref AccessEntry]) void = trust {- for e in es {- if e.public_key.ptr != none {- bytes.free_ptr(e.public_key.ptr)- }- if e.name.ptr != none && e.name.ptr != e.public_key.ptr {- bytes.free_ptr(e.name.ptr)- }- val ep: mut ref void = e as ref void- @free(ep)- }- @listfree(es)-}--pub fn empty() Access = {- return Access{- valid: true,- error_line: 0,- anonymous_read: false,- entries: lists.new[ref AccessEntry]()- }-}--fn invalid(line: i64) Access = {- return Access{- valid: false,- error_line: line,- anonymous_read: false,- entries: lists.new[ref AccessEntry]()- }-}--pub fn free(a: Access) void = trust {- free_entries(a.entries)-}--fn find(es: list[ref AccessEntry], public_key: bytes.Bytes) option[usize] = trust {- val i: mut usize = 0- for i < @len(es) {- val o = @get(es, i)- if o is some e {- if bytes.Bytes.eql(e.public_key, public_key) {- return some i- }- }- i++- }- return none-}--fn parse(text: bytes.Bytes) Access = trust {- val acc: mut Access = empty()- val start: mut usize = 0- val line_no: mut i64 = 0- val i: mut usize = 0- for i <= text.len {- if i == text.len || bytes.Bytes.at(text, i) == 10 {- line_no++- val line: bytes.Bytes = trim(bytes.Bytes.slice(text, start, i))- if line.len > 0 && bytes.Bytes.at(line, 0) != 35 {- val toks: list[bytes.Bytes] = tokenize(line)- val nt: usize = @len(toks)- val bad: mut bool = false- if nt == 2 && bytes.Bytes.eql(token(toks, 0), bytes.bytes(c"anonymous", 9)) {- if bytes.Bytes.eql(token(toks, 1), bytes.bytes(c"read", 4)) {- acc.anonymous_read = true- } else {- bad = true- }- } elif nt >= 3 && bytes.Bytes.eql(token(toks, 0), bytes.bytes(c"allow", 5)) {- val role_t: bytes.Bytes = token(toks, 1)- val role: mut u8 = 0- if bytes.Bytes.eql(role_t, bytes.bytes(c"read", 4)) {- role = ROLE_READ- } elif bytes.Bytes.eql(role_t, bytes.bytes(c"write", 5)) {- role = ROLE_WRITE- } else {- bad = true- }- val pub_opt = ed.parse_public(token(toks, 2))- val public_key: mut bytes.Bytes = bytes.empty()- match pub_opt {- some p => {- public_key = p- }- none => {- bad = true- }- }- if !bad {- if find(acc.entries, public_key) is some _ {- bad = true- } else {- val e: mut ref AccessEntry = @alloc(@sizeof(AccessEntry)) as ref AccessEntry- e.role = role as u64- e.public_key = public_key- e.name = bytes.empty()- if nt >= 4 {- e.name = bytes.Bytes.dup(token(toks, 3))- }- @append(acc.entries, e)- public_key = bytes.empty()- }- }- if public_key.ptr != none {- bytes.free_owned(public_key)- }- } else {- bad = true- }- @listfree(toks)- if bad {- free(acc)- return invalid(line_no)- }- }- start = i + 1- }- i++- }- return acc-}--pub fn load(repo: layout.Repo) Access = trust {- val p: str.StringView = path(repo)- val z: ref u8 = bytes.Bytes.to_cstr(bytes.bytes(p.ptr, p.len))- val mode: i32 = tls.file_mode(z)- if mode >= 0 && (mode & 18) != 0 {- files.free_path(p)- @free(z as ref void)- return invalid(0)- }- val data_opt = files.read_all(p)- files.free_path(p)- @free(z as ref void)- val data: mut bytes.Bytes = bytes.empty()- match data_opt {- some d => {- data = d- }- none => {- return empty()- }- }- val acc: Access = parse(data)- files.free_buffer(data)- return acc-}--/// The role granted to `pub`, or 0 for anonymous, or 255 when unknown.-pub fn role_for(a: Access, public_key: bytes.Bytes) u8 = trust {- if public_key.ptr == none {- if a.anonymous_read {- return ROLE_READ- }- return ROLE_ANONYMOUS- }- val idx = find(a.entries, public_key)- if idx is some i {- val o = @get(a.entries, i)- if o is some e {- return e.role as u8- }- }- return 255-}--pub fn write(repo: layout.Repo, a: Access) bool = trust {- val b: mut buf.Buf = buf.new(128)- buf.Buf.put_raw(b, c"# veins access policy\n" as ref u8, 22)- if a.anonymous_read {- buf.Buf.put_raw(b, c"anonymous read\n" as ref u8, 15)- }- for e in a.entries {- val nm: bytes.Bytes = e.name- if nm.len > 64 || e.public_key.len != 32 {- buf.Buf.free(b)- return false- }- buf.Buf.put_raw(b, c"allow " as ref u8, 6)- if e.role == (ROLE_WRITE as u64) {- buf.Buf.put_raw(b, c"write" as ref u8, 5)- } else {- buf.Buf.put_raw(b, c"read" as ref u8, 4)- }- buf.Buf.put_u8(b, 32)- val pub_enc: bytes.Bytes = ed.format_public(e.public_key)- buf.Buf.put_bytes(b, pub_enc)- bytes.free_owned(pub_enc)- if nm.len > 0 {- buf.Buf.put_u8(b, 32)- buf.Buf.put_bytes(b, nm)- }- buf.Buf.put_u8(b, 10)- }- val out: bytes.Bytes = bytes.Bytes.dup(buf.Buf.view(b))- buf.Buf.free(b)- val p: str.StringView = path(repo)- val passed: bool = files.write_all(p, out)- val z: ref u8 = bytes.Bytes.to_cstr(bytes.bytes(p.ptr, p.len))- val mode_rc: i32 = tls.chmod(z, 384)- bytes.free_ptr(z)- files.free_path(p)- bytes.free_owned(out)- if mode_rc < 0 {- }- return passed-}--pub fn add(repo: layout.Repo, role: u8, public_key: bytes.Bytes, name: bytes.Bytes) bool = trust {- val mut_acc: mut Access = load(repo)- if !mut_acc.valid {- free(mut_acc)- return false- }- if find(mut_acc.entries, public_key) is some _ {- free(mut_acc)- return false- }- val e: mut ref AccessEntry = @alloc(@sizeof(AccessEntry)) as ref AccessEntry- e.role = role as u64- e.public_key = bytes.Bytes.dup(public_key)- e.name = bytes.Bytes.dup(name)- @append(mut_acc.entries, e)- val passed: bool = write(repo, mut_acc)- free(mut_acc)- return passed-}--pub fn remove(repo: layout.Repo, fingerprint: bytes.Bytes, name: bytes.Bytes) bool = trust {- val mut_acc: mut Access = load(repo)- if !mut_acc.valid {- free(mut_acc)- return false- }- val kept: mut list[ref AccessEntry] = lists.new[ref AccessEntry]()- val removed: mut bool = false- for e in mut_acc.entries {- val match_fp: mut bool = false- if fingerprint.len > 0 {- val fp_opt = ed.fingerprint(e.public_key)- if fp_opt is some fp {- match_fp = bytes.Bytes.eql(fp, fingerprint)- bytes.free_owned(fp)- }- }- val match_name: bool = name.len > 0 && bytes.Bytes.eql(e.name, name)- if match_fp || match_name {- removed = true- if e.public_key.ptr != none {- bytes.free_ptr(e.public_key.ptr)- }- if e.name.ptr != none {- bytes.free_ptr(e.name.ptr)- }- val ep2: mut ref void = e as ref void- @free(ep2)- } else {- @append(kept, e)- }- }- @listfree(mut_acc.entries)- mut_acc.entries = kept- val passed: bool = removed && write(repo, mut_acc)- free(mut_acc)- return passed-}--pub fn set_anonymous(repo: layout.Repo, on: bool) bool = trust {- val mut_acc: mut Access = load(repo)- if !mut_acc.valid {- free(mut_acc)- return false- }- mut_acc.anonymous_read = on- val passed: bool = write(repo, mut_acc)- free(mut_acc)- return passed-}--- a/veins/src/auth/credentials.sx+++ /dev/null@@ -1,395 +0,0 @@-/// Per-user native-protocol credentials.-///-/// Key names are stored as one small file per target under `.../veins/auth/`.-/// The directory never contains private key material. `default` is the global-/// fallback; other entries are host or host:port names.-///-/// Resolution order in commands is: explicit `-key:`, repository remote key,-/// then this directory (host, host without port, default).--val str = use("std/string")-val bytes = use("../core/bytes.sx")-val lists = use("../core/lists.sx")-val files = use("../io/files.sx")-val keys = use("keys.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 lower(b: bytes.Bytes) bytes.Bytes = trust {- val out: ref u8 = @alloc(b.len) as ref u8- val i: mut usize = 0- for i < b.len {- val c: u8 = bytes.Bytes.at(b, i)- if c >= 65 && c <= 90 {- @store8(@ptradd(out, i as i64), (c + 32) as u8)- } else {- @store8(@ptradd(out, i as i64), c)- }- i++- }- return bytes.bytes(out, b.len)-}--fn find_from(hay: bytes.Bytes, needle: bytes.Bytes, from: usize) i64 = trust {- if needle.len == 0 || needle.len > hay.len {- return -1- }- val i: mut usize = from- for i <= hay.len - needle.len {- if bytes.Bytes.eql(bytes.Bytes.slice(hay, i, i + needle.len), needle) {- return i as i64- }- i++- }- return -1-}--fn auth_dir() bytes.Bytes = trust {- val dir: bytes.Bytes = keys.key_dir()- val last: mut i64 = -1- val i: mut usize = 0- for i < dir.len {- if bytes.Bytes.at(dir, i) == 47 {- last = i as i64- }- i++- }- if last <= 0 {- bytes.free_owned(dir)- return bytes.Bytes.dup(bytes.bytes(c".veins-auth", 11))- }- val base: bytes.Bytes = bytes.Bytes.slice(dir, 0, last as usize)- val joined: str.StringView = files.join(files.to_view(base), str.from_cstr(c"auth"))- val out: bytes.Bytes = bytes.Bytes.dup(bytes.bytes(joined.ptr, joined.len))- files.free_path(joined)- bytes.free_owned(dir)- return out-}--fn hex_char(v: u8) u8 = {- if v < 10 {- return (48 + v) as u8- }- return (87 + v) as u8-}--fn hex_encode(b: bytes.Bytes) bytes.Bytes = trust {- val out: ref u8 = @alloc(b.len * 2) as ref u8- val i: mut usize = 0- for i < b.len {- val c: u8 = bytes.Bytes.at(b, i)- @store8(@ptradd(out, (i * 2) as i64), hex_char(c >> 4))- @store8(@ptradd(out, (i * 2 + 1) as i64), hex_char(c & 15))- i++- }- return bytes.bytes(out, b.len * 2)-}--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- }- return -1-}--fn hex_decode(b: bytes.Bytes) option[bytes.Bytes] = trust {- if b.len == 0 || b.len % 2 != 0 {- return none- }- val out: ref u8 = @alloc(b.len / 2) as ref u8- val i: mut usize = 0- for i < b.len / 2 {- val hi: i32 = hex_value(bytes.Bytes.at(b, i * 2))- val lo: i32 = hex_value(bytes.Bytes.at(b, i * 2 + 1))- if hi < 0 || lo < 0 {- @free(out as ref void)- return none- }- @store8(@ptradd(out, i as i64), ((hi << 4) | lo) as u8)- i++- }- return some bytes.bytes(out, b.len / 2)-}--fn target_path(dir: bytes.Bytes, target: bytes.Bytes) bytes.Bytes = trust {- val encoded: bytes.Bytes = hex_encode(target)- val joined: str.StringView = files.join(files.to_view(dir), files.to_view(encoded))- val out: bytes.Bytes = bytes.Bytes.dup(bytes.bytes(joined.ptr, joined.len))- files.free_path(joined)- bytes.free_owned(encoded)- return out-}--fn read_key(path: bytes.Bytes) option[bytes.Bytes] = trust {- val data_opt = files.read_all(files.to_view(path))- val data: mut bytes.Bytes = bytes.empty()- match data_opt {- some d => {- data = d- }- none => {- return none- }- }- val value: bytes.Bytes = trim(data)- if value.len == 0 {- files.free_buffer(data)- return none- }- val out: bytes.Bytes = bytes.Bytes.dup(value)- files.free_buffer(data)- return some out-}--fn lookup(dir: bytes.Bytes, target: bytes.Bytes) option[bytes.Bytes] = trust {- val path: bytes.Bytes = target_path(dir, target)- val out = read_key(path)- bytes.free_owned(path)- return out-}--fn strip_authority_user(authority: bytes.Bytes) bytes.Bytes = trust {- val last: mut i64 = -1- val i: mut usize = 0- for i < authority.len {- if bytes.Bytes.at(authority, i) == 64 {- last = i as i64- }- i++- }- if last >= 0 {- return bytes.Bytes.slice(authority, (last as usize) + 1, authority.len)- }- return authority-}--fn authority_of(input: bytes.Bytes) option[bytes.Bytes] = trust {- val scheme: i64 = find_from(input, bytes.bytes(c"://", 3), 0)- val start: mut usize = 0- if scheme >= 0 {- start = (scheme as usize) + 3- }- if start >= input.len {- return none- }- val slash: i64 = find_from(input, bytes.bytes(c"/", 1), start)- val end: mut usize = input.len- if slash >= 0 {- end = slash as usize- }- if end <= start {- return none- }- val raw: bytes.Bytes = bytes.Bytes.slice(input, start, end)- val host: bytes.Bytes = strip_authority_user(raw)- if host.len == 0 {- return none- }- return some lower(host)-}--/// Normalize an auth target. `default` is the global fallback; otherwise the-/// target is a host or host:port extracted from a URL when necessary.-pub fn normalize_target(input: bytes.Bytes) bytes.Bytes = trust {- val t: bytes.Bytes = trim(input)- if t.len == 0 || bytes.Bytes.eql(t, bytes.bytes(c"default", 7)) {- return bytes.Bytes.dup(bytes.bytes(c"default", 7))- }- val auth = authority_of(t)- if auth is some a {- val out: bytes.Bytes = bytes.Bytes.dup(a)- bytes.free_owned(a)- return out- }- val slash: i64 = find_from(t, bytes.bytes(c"/", 1), 0)- val end: mut usize = t.len- if slash >= 0 {- end = slash as usize- }- val raw: bytes.Bytes = bytes.Bytes.slice(t, 0, end)- val host: bytes.Bytes = strip_authority_user(raw)- if host.len == 0 {- return bytes.Bytes.dup(bytes.bytes(c"default", 7))- }- return lower(host)-}--/// Store or replace a key mapping.-pub fn set_key(target: bytes.Bytes, name: bytes.Bytes) bool = trust {- if target.len == 0 || name.len == 0 {- return false- }- val dir: bytes.Bytes = auth_dir()- if !files.exists_dir(files.to_view(dir)) {- if !files.mkdir_all(files.to_view(dir)) {- bytes.free_owned(dir)- return false- }- }- val path: bytes.Bytes = target_path(dir, target)- val passed: bool = files.write_all(files.to_view(path), name)- bytes.free_owned(path)- bytes.free_owned(dir)- return passed-}--pub fn remove_key(target: bytes.Bytes) bool = trust {- val dir: bytes.Bytes = auth_dir()- val path: bytes.Bytes = target_path(dir, target)- val removed: bool = files.delete(files.to_view(path))- bytes.free_owned(path)- bytes.free_owned(dir)- return removed-}--pub fn list_lines() list[bytes.Bytes] = trust {- val out: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()- val dir: bytes.Bytes = auth_dir()- if !files.exists_dir(files.to_view(dir)) {- bytes.free_owned(dir)- return out- }- val names: list[ref u8] = files.list_dir(files.to_view(dir))- for n in names {- val encoded: bytes.Bytes = bytes.from_cstr(n)- val decoded = hex_decode(encoded)- if decoded is some target {- val path: bytes.Bytes = target_path(dir, target)- val key_opt = read_key(path)- bytes.free_owned(path)- if key_opt is some key {- val line: ref u8 = @fmtalloc("{s}: {s}\n", {- str.view(target.ptr, target.len as i64),- str.view(key.ptr, key.len as i64)- })- @append(out, bytes.Bytes.dup(bytes.from_cstr(line)))- @free(line as ref void)- bytes.free_owned(key)- }- bytes.free_owned(target)- }- }- files.free_names(names)- bytes.free_owned(dir)- return out-}--fn host_without_port(host: bytes.Bytes) option[bytes.Bytes] = trust {- if host.len == 0 || bytes.Bytes.at(host, 0) == 91 {- return none- }- val last: mut i64 = -1- val i: mut usize = 0- for i < host.len {- if bytes.Bytes.at(host, i) == 58 {- last = i as i64- }- i++- }- if last <= 0 {- return none- }- return some bytes.Bytes.slice(host, 0, last as usize)-}--/// True when `name` refers to a usable local key file.-pub fn local_key_exists(name: bytes.Bytes) bool = trust {- if name.len == 0 {- return false- }- if bytes.Bytes.starts_with(name, bytes.bytes(c"ed25519:", 8)) {- return false- }- val key_opt = keys.load(name)- match key_opt {- some k => {- keys.free_key(k)- return true- }- none => {- return false- }- }-}--/// Resolve the key for a native URL: host:port, then host, then default.-pub fn key_for_url(url: bytes.Bytes) option[bytes.Bytes] = trust {- val dir: bytes.Bytes = auth_dir()- val host_opt = authority_of(url)- if host_opt is some host {- val exact = lookup(dir, host)- if exact is some k {- bytes.free_owned(host)- bytes.free_owned(dir)- return some k- }- val no_port = host_without_port(host)- if no_port is some h {- val base = lookup(dir, h)- if base is some k {- bytes.free_owned(host)- bytes.free_owned(dir)- return some k- }- }- bytes.free_owned(host)- }- val fallback = lookup(dir, bytes.bytes(c"default", 7))- bytes.free_owned(dir)- if fallback is some k {- return some k- }- return none-}--test "auth targets normalize hosts and URLs" {- trust {- val a: bytes.Bytes = normalize_target(bytes.bytes(- c"veins://User@Forge.Example.com:7419/alice/repo",- 46- ))- assert bytes.Bytes.eql(a, bytes.bytes(c"forge.example.com:7419", 22))- bytes.free_owned(a)- val b: bytes.Bytes = normalize_target(bytes.bytes(c"ssh://git@Example.com:22/x", 26))- assert bytes.Bytes.eql(b, bytes.bytes(c"example.com:22", 14))- bytes.free_owned(b)- val c: bytes.Bytes = normalize_target(bytes.bytes(c"default", 7))- assert bytes.Bytes.eql(c, bytes.bytes(c"default", 7))- bytes.free_owned(c)- }-}--test "auth target hex round trip" {- trust {- val a: bytes.Bytes = hex_encode(bytes.bytes(c"forge.example.com:7419", 22))- val b = hex_decode(a)- if b is some raw {- assert bytes.Bytes.eql(raw, bytes.bytes(c"forge.example.com:7419", 22))- bytes.free_owned(raw)- } else {- assert false- }- bytes.free_owned(a)- }-}--- a/veins/src/auth/handshake.sx+++ /dev/null@@ -1,35 +0,0 @@-/// Shared handshake message construction and role checks.--val bytes = use("../core/bytes.sx")-val buf = use("../core/buf.sx")--pub fn auth_message(- version: u16,- repo: bytes.Bytes,- server_nonce: bytes.Bytes,- client_nonce: bytes.Bytes,- binding: bytes.Bytes-) bytes.Bytes = trust {- val b: mut buf.Buf = buf.new(128)- buf.Buf.put_raw(b, c"veins-auth/1" as ref u8, 12)- buf.Buf.put_u8(b, 0)- buf.Buf.put_u8(b, ((version >> 8) & 255) as u8)- buf.Buf.put_u8(b, (version & 255) as u8)- buf.Buf.put_length_prefixed(b, repo)- buf.Buf.put_bytes(b, server_nonce)- buf.Buf.put_bytes(b, client_nonce)- buf.Buf.put_bytes(b, binding)- val out: bytes.Bytes = bytes.Bytes.dup(buf.Buf.view(b))- buf.Buf.free(b)- return out-}--pub fn role_name(role: u8) bytes.Bytes = {- if role == 2 {- return bytes.bytes(c"write", 5)- }- if role == 1 {- return bytes.bytes(c"read", 4)- }- return bytes.bytes(c"anonymous", 9)-}--- a/veins/src/auth/keys.sx+++ /dev/null@@ -1,259 +0,0 @@-/// Client-side Ed25519 key storage.--val str = use("std/string")-val os = use("std/os")-val bytes = use("../core/bytes.sx")-val lists = use("../core/lists.sx")-val files = use("../io/files.sx")-val ed = use("../crypto/ed25519.sx")-val tls = use("../crypto/tls.sx")-val random = use("std/crypto/random")--pub type Key = {- name: mut bytes.Bytes- seed: mut bytes.Bytes- public_key: mut bytes.Bytes- fingerprint: mut bytes.Bytes-}--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- }- }-}--pub fn key_dir() bytes.Bytes = trust {- val xdg = env_dup(c"XDG_CONFIG_HOME")- if xdg is some base {- val out: str.StringView = files.join(- files.to_view(base),- str.from_cstr(c"veins/keys")- )- files.free_buffer(base)- return bytes.bytes(out.ptr, out.len)- }- val home = env_dup(c"HOME")- if home is some h {- val out2: str.StringView = files.join(- files.to_view(h),- str.from_cstr(c".config/veins/keys")- )- files.free_buffer(h)- return bytes.bytes(out2.ptr, out2.len)- }- return bytes.Bytes.dup(bytes.bytes(c".veins-keys", 11))-}--pub fn key_path(name: bytes.Bytes) bytes.Bytes = trust {- val dir: bytes.Bytes = key_dir()- val fname: ref u8 = @alloc(name.len + 5) as ref u8- @memcpy(fname as ref void, name.ptr as ref void, name.len)- @memcpy(@ptradd(fname, name.len as i64) as ref void, c".key" as ref void, 4)- @store8(@ptradd(fname, (name.len + 4) as i64), 0)- val joined: str.StringView = files.join(- files.to_view(dir),- str.view(fname, (name.len + 4) as i64)- )- bytes.free_owned(dir)- @free(fname as ref void)- return bytes.bytes(joined.ptr, joined.len)-}--fn mkdirs(path: bytes.Bytes) bool = trust {- if files.exists_dir(files.to_view(path)) {- return true- }- val i: mut usize = 1- for i < path.len {- if bytes.Bytes.at(path, i) == 47 {- val part: str.StringView = str.view(path.ptr, i as i64)- files.mkdir_all(part)- }- i++- }- return files.mkdir_all(files.to_view(path))-}--fn valid_name(name: bytes.Bytes) bool = trust {- if name.len == 0 || name.len > 128 {- return false- }- val i: mut usize = 0- for i < name.len {- val c: u8 = bytes.Bytes.at(name, i)- if c == 47 || c == 92 || c == 0 {- return false- }- i++- }- return true-}--pub fn load(name: bytes.Bytes) option[Key] = trust {- val p: bytes.Bytes = key_path(name)- val z: ref u8 = bytes.Bytes.to_cstr(p)- val mode: i32 = tls.file_mode(z)- if mode < 0 || (mode & 63) != 0 {- bytes.free_owned(p)- @free(z as ref void)- return none- }- val data_opt = files.read_all(files.to_view(p))- bytes.free_owned(p)- @free(z as ref void)- val data: mut bytes.Bytes = bytes.empty()- match data_opt {- some d => {- data = d- }- none => {- return none- }- }- if data.len != 33 || bytes.Bytes.at(data, 0) != 1 {- files.free_buffer(data)- return none- }- val seed: bytes.Bytes = bytes.Bytes.dup(bytes.Bytes.slice(data, 1, 33))- files.free_buffer(data)- val pub_opt = ed.public_from_seed(seed)- val public_key: mut bytes.Bytes = bytes.empty()- match pub_opt {- some v => {- public_key = v- }- none => {- bytes.free_owned(seed)- return none- }- }- val fp_opt = ed.fingerprint(public_key)- val fp: mut bytes.Bytes = bytes.empty()- match fp_opt {- some v => {- fp = v- }- none => {- bytes.free_owned(seed)- bytes.free_owned(public_key)- return none- }- }- return some Key{- name: bytes.Bytes.dup(name),- seed: seed,- public_key: public_key,- fingerprint: fp- }-}--pub fn free_key(k: Key) void = trust {- if k.name.ptr != none {- bytes.free_ptr(k.name.ptr)- }- if k.seed.ptr != none {- bytes.free_ptr(k.seed.ptr)- }- if k.public_key.ptr != none {- bytes.free_ptr(k.public_key.ptr)- }- if k.fingerprint.ptr != none {- bytes.free_ptr(k.fingerprint.ptr)- }-}--pub fn generate(name: bytes.Bytes) option[Key] = trust {- if !valid_name(name) {- return none- }- val dir: bytes.Bytes = key_dir()- if !mkdirs(dir) {- bytes.free_owned(dir)- return none- }- val zdir: ref u8 = bytes.Bytes.to_cstr(dir)- tls.chmod(zdir, 448)- @free(zdir as ref void)- bytes.free_owned(dir)- val seed: ref u8 = @alloc(32) as ref u8- random.random_bytes(seed as ref void, 32)- val seed_b: bytes.Bytes = bytes.bytes(seed, 32)- val pub_opt = ed.public_from_seed(seed_b)- val public_key: mut bytes.Bytes = bytes.empty()- match pub_opt {- some v => {- public_key = v- }- none => {- @free(seed as ref void)- return none- }- }- val fp_opt = ed.fingerprint(public_key)- val fp: mut bytes.Bytes = bytes.empty()- match fp_opt {- some v => {- fp = v- }- none => {- @free(seed as ref void)- bytes.free_owned(public_key)- return none- }- }- val p: bytes.Bytes = key_path(name)- val body: ref u8 = @alloc(33) as ref u8- @store8(body, 1)- @memcpy(@ptradd(body, 1) as ref void, seed as ref void, 32)- val wrote: bool = files.write_all(files.to_view(p), bytes.bytes(body, 33))- @free(body as ref void)- val z: ref u8 = bytes.Bytes.to_cstr(p)- tls.chmod(z, 384)- @free(z as ref void)- bytes.free_owned(p)- if !wrote {- @free(seed as ref void)- bytes.free_owned(public_key)- bytes.free_owned(fp)- return none- }- return some Key{- name: bytes.Bytes.dup(name),- seed: seed_b,- public_key: public_key,- fingerprint: fp- }-}--pub fn list_names() list[bytes.Bytes] = trust {- val out: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()- val dir: bytes.Bytes = key_dir()- val dview: str.StringView = files.to_view(dir)- if files.exists_dir(dview) {- val names: list[ref u8] = files.list_dir(dview)- for n in names {- val len: i64 = @strlen(n)- if len > 4 && files.name_ends_with(n, c".key") {- @append(out, bytes.Bytes.dup(bytes.bytes(n, (len - 4) as usize)))- }- }- files.free_names(names)- }- bytes.free_owned(dir)- return out-}--pub fn free_names(names: list[bytes.Bytes]) void = trust {- for n in names {- if n.ptr != none {- bytes.free_owned(n)- }- }- @listfree(names)-}--- a/veins/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/veins/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/veins/src/chunking/gear.bin and b/veins/src/chunking/gear.bin differ--- a/veins/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/veins/src/cli/access_cmd.sx+++ /dev/null@@ -1,240 +0,0 @@-/// `vn access`: manage a served repository's access file.--val stdio = use("std/stdio")-val str = use("std/string")-val bytes = use("../core/bytes.sx")-val files = use("../io/files.sx")-val layout = use("../store/layout.sx")-val access = use("../auth/access.sx")-val ed = use("../crypto/ed25519.sx")-val cmsg = use("../core/msg.sx")--fn trim_text(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 != 10 && c != 13 {- break- }- start++- }- for end > start {- val c2: u8 = bytes.Bytes.at(b, end - 1)- if c2 != 32 && c2 != 9 && c2 != 10 && c2 != 13 {- break- }- end--- }- return bytes.Bytes.slice(b, start, end)-}--fn read_public(arg: bytes.Bytes) option[bytes.Bytes] = trust {- if bytes.Bytes.starts_with(arg, bytes.bytes(c"ed25519:", 8)) {- return ed.parse_public(arg)- }- val p: str.StringView = files.to_view(arg)- val data_opt = files.read_all(p)- if data_opt is some d {- val t: bytes.Bytes = trim_text(d)- val parsed = ed.parse_public(t)- if parsed is some v {- files.free_buffer(d)- return some v- }- files.free_buffer(d)- }- return none-}--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 => {- cmsg.error_prefix()- stdio.eprint("expected access subcommand\n", {})- return 1- }- }- val path: str.StringView = str.from_cstr(c".")- val repo_opt = layout.discover(path)- val repo: mut layout.Repo = layout.Repo{root: bytes.empty()}- match repo_opt {- some r => {- repo = r- }- none => {- cmsg.error_prefix()- stdio.eprint("not a veins repository\n", {})- return 1- }- }- if @strcmp(sub, c"add") == 0 {- val role: mut bytes.Bytes = bytes.empty()- val key_arg: mut bytes.Bytes = bytes.empty()- val name: mut bytes.Bytes = bytes.empty()- val i: mut usize = start + 1- for i < @len(args) {- val o = @get(args, i)- if o is some a {- val av: bytes.Bytes = bytes.from_cstr(a)- if bytes.Bytes.eql(av, bytes.bytes(c"-role", 5)) && i + 1 < @len(args) {- val v = @get(args, i + 1)- if v is some rv {- role = bytes.from_cstr(rv)- i++- }- } elif bytes.Bytes.eql(av, bytes.bytes(c"-key", 4)) && i + 1 < @len(args) {- val v = @get(args, i + 1)- if v is some rv {- key_arg = bytes.from_cstr(rv)- i++- }- } elif bytes.Bytes.eql(av, bytes.bytes(c"-name", 5)) && i + 1 < @len(args) {- val v = @get(args, i + 1)- if v is some rv {- name = bytes.from_cstr(rv)- i++- }- } else {- cmsg.error_prefix()- stdio.eprint("unknown access add option: {s}\n", {str.from_cstr(a)})- layout.free_repo(repo)- return 1- }- }- i++- }- if role.ptr == none || key_arg.ptr == none {- cmsg.error_prefix()- stdio.eprint("access add requires -role and -key\n", {})- layout.free_repo(repo)- return 1- }- val role_code: mut u8 = access.ROLE_READ- if bytes.Bytes.eql(role, bytes.bytes(c"write", 5)) {- role_code = access.ROLE_WRITE- } elif !bytes.Bytes.eql(role, bytes.bytes(c"read", 4)) {- cmsg.error_prefix()- stdio.eprint("role must be read or write\n", {})- layout.free_repo(repo)- return 1- }- val pub_opt = read_public(key_arg)- if pub_opt is none {- cmsg.error_prefix()- stdio.eprint("invalid public key\n", {})- layout.free_repo(repo)- return 1- }- val public_key: mut bytes.Bytes = bytes.empty()- if pub_opt is some pk {- public_key = pk- } else {- cmsg.error_prefix()- stdio.eprint("invalid public key\n", {})- layout.free_repo(repo)- return 1- }- val passed: bool = access.add(repo, role_code, public_key, name)- bytes.free_owned(public_key)- layout.free_repo(repo)- if !passed {- cmsg.error_prefix()- stdio.eprint("cannot add key\n", {})- return 1- }- cmsg.info_prefix()- stdio.print("access granted\n", {})- return 0- }- if @strcmp(sub, c"list") == 0 {- val a: access.Access = access.load(repo)- layout.free_repo(repo)- if !a.valid {- cmsg.error_prefix()- stdio.eprint("invalid access file at line {d}\n", {a.error_line})- access.free(a)- return 1- }- if a.anonymous_read {- stdio.print("anonymous: read\n", {})- } else {- stdio.print("anonymous: off\n", {})- }- for e in a.entries {- val fp_opt = ed.fingerprint(e.public_key)- val role: mut bytes.Bytes = bytes.bytes(c"read", 4)- if e.role == (access.ROLE_WRITE as u64) {- role = bytes.bytes(c"write", 5)- }- if fp_opt is some fp {- stdio.print(- "{s} {s} {s}\n",- {- str.view(role.ptr, role.len as i64),- str.view(fp.ptr, fp.len as i64),- str.view(e.name.ptr, e.name.len as i64)- }- )- bytes.free_owned(fp)- }- }- access.free(a)- return 0- }- if @strcmp(sub, c"remove") == 0 {- val arg_opt = @get(args, start + 1)- val arg: mut bytes.Bytes = bytes.empty()- if arg_opt is some a {- arg = bytes.from_cstr(a)- } else {- cmsg.error_prefix()- stdio.eprint("access remove requires a fingerprint or name\n", {})- layout.free_repo(repo)- return 1- }- val is_fp: bool = arg.len == 26- val fp: mut bytes.Bytes = bytes.empty()- val nm: mut bytes.Bytes = bytes.empty()- if is_fp {- fp = arg- } else {- nm = arg- }- val passed: bool = access.remove(repo, fp, nm)- layout.free_repo(repo)- if !passed {- cmsg.error_prefix()- stdio.eprint("key not found or cannot write access file\n", {})- return 1- }- cmsg.info_prefix()- stdio.print("access removed\n", {})- return 0- }- if @strcmp(sub, c"anonymous") == 0 {- val arg_opt = @get(args, start + 1)- val on: mut bool = false- if arg_opt is some a {- val v: bytes.Bytes = bytes.from_cstr(a)- on = bytes.Bytes.eql(v, bytes.bytes(c"on", 2))- }- val passed: bool = access.set_anonymous(repo, on)- layout.free_repo(repo)- if !passed {- cmsg.error_prefix()- stdio.eprint("cannot update access file\n", {})- return 1- }- return 0- }- layout.free_repo(repo)- cmsg.error_prefix()- stdio.eprint("unknown access subcommand: {s}\n", {str.from_cstr(sub)})- return 1-}--- a/veins/src/cli/auth_cmd.sx+++ /dev/null@@ -1,114 +0,0 @@-/// `vn auth`: remember which Ed25519 key to use for a host or by default.--val stdio = use("std/stdio")-val str = use("std/string")-val bytes = use("../core/bytes.sx")-val keys = use("../auth/keys.sx")-val credentials = use("../auth/credentials.sx")-val cmsg = use("../core/msg.sx")--fn usage() void = trust {- stdio.eprint("usage: vn auth <use|list|remove> ...\n", {})- stdio.eprint(" vn auth use <key> [<host|url>] set the default or host key\n", {})- stdio.eprint(" vn auth list show stored key mappings\n", {})- stdio.eprint(" vn auth remove [<host|url>] remove a mapping (default if omitted)\n", {})-}--fn arg(args: list[ref u8], i: usize) bytes.Bytes = trust {- val o = @get(args, i)- if o is some v {- return bytes.from_cstr(v)- }- return bytes.empty()-}--pub fn run(args: list[ref u8], start: usize) i32 = trust {- val sub_opt = @get(args, start)- if sub_opt is none {- usage()- return 1- }- val sub: mut ref u8 = none- match sub_opt {- some s => {- sub = s- }- none => {- return 1- }- }- if @strcmp(sub, c"use") == 0 {- val name: bytes.Bytes = arg(args, start + 1)- if name.len == 0 {- usage()- return 1- }- val key_opt = keys.load(name)- if key_opt is none {- cmsg.error_prefix()- stdio.eprint("key not found or has unsafe permissions: {s}\n", {- str.view(name.ptr, name.len as i64)- })- return 1- }- match key_opt {- some k => {- keys.free_key(k)- }- none => {- return 1- }- }- val target: bytes.Bytes = credentials.normalize_target(arg(args, start + 2))- val passed: bool = credentials.set_key(target, name)- if passed {- if bytes.Bytes.eql(target, bytes.bytes(c"default", 7)) {- stdio.print("default key set to {s}\n", {str.view(name.ptr, name.len as i64)})- } else {- stdio.print("key for {s} set to {s}\n", {- str.view(target.ptr, target.len as i64),- str.view(name.ptr, name.len as i64)- })- }- } else {- cmsg.error_prefix()- stdio.eprint("cannot write auth configuration\n", {})- }- bytes.free_owned(target)- if passed {- return 0- }- return 1- }- if @strcmp(sub, c"list") == 0 {- val lines: list[bytes.Bytes] = credentials.list_lines()- if @len(lines) == 0 {- stdio.print("no stored credentials\n", {})- }- for line in lines {- stdio.print("{s}", {str.view(line.ptr, line.len as i64)})- bytes.free_owned(line)- }- @listfree(lines)- return 0- }- if @strcmp(sub, c"remove") == 0 {- val target: bytes.Bytes = credentials.normalize_target(arg(args, start + 1))- val removed: bool = credentials.remove_key(target)- if removed {- stdio.print("removed {s}\n", {str.view(target.ptr, target.len as i64)})- } else {- cmsg.error_prefix()- stdio.eprint("no credential for {s}\n", {str.view(target.ptr, target.len as i64)})- }- bytes.free_owned(target)- if removed {- return 0- }- return 1- }- cmsg.error_prefix()- stdio.eprint("unknown auth subcommand: {s}\n", {str.from_cstr(sub)})- usage()- return 1-}--- a/veins/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/veins/src/cli/bookmark_cmd.sx+++ /dev/null@@ -1,617 +0,0 @@-/// `vn bmk`: manage named, movable pointers (branches).-///-/// Bookmarks are the branching primitive. `vn bmk set <name>` creates or-/// moves one, `vn new <name>` starts a change on top of it, and `vn co <name>`-/// switches the working copy to it. Rewriting a working-copy commit (through a-/// snapshot, `describe`, or `rm`) moves any bookmark that named that commit.--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 buf = use("../core/buf.sx")-val lists = use("../core/lists.sx")-val prim = use("../core/primitives.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 store = use("../store/store.sx")-val layout = use("../store/layout.sx")-val state = use("../store/state.sx")-val repoconfig = use("../core/repoconfig.sx")-val txn = use("../store/txn.sx")-val viewops = use("../store/viewops.sx")-val snapshot = use("../worktree/snapshot.sx")--fn cmd_is(a: ref u8, text: ref u8, len: usize) bool = trust {- 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 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 free_id(id: objid.Id) void = trust {- if id.ptr != none {- val p: mut ref void = id.ptr as ref void- @free(p)- }-}--/// Copy a byte span with a trailing NUL so it can be passed to the formatted-/// output helpers safely. The reported length excludes the terminator.-fn dup_z(b: bytes.Bytes) bytes.Bytes = trust {- val out: ref u8 = @alloc(b.len + 1) as ref u8- if b.len > 0 {- @memcpy(out as ref void, b.ptr as ref void, b.len)- }- @store8(@ptradd(out, b.len as i64), 0)- return bytes.bytes(out, b.len)-}--fn free_targets(ts: view.TargetSet) void = trust {- // Target IDs are borrowed from the decoded view body. Only the lists are- // owned by the view.- @listfree(ts.adds)- @listfree(ts.removes)-}--fn contains_seq(name: bytes.Bytes, needle: bytes.Bytes) bool = trust {- if needle.len == 0 || needle.len > name.len {- return false- }- val last: usize = name.len - needle.len- val i: mut usize = 0- for i <= last {- if bytes.Bytes.eql(bytes.Bytes.slice(name, i, i + needle.len), needle) {- return true- }- i++- }- return false-}--/// Ref names used as git branches. The data model accepts nearly anything, but-/// a bookmark that cannot be exported as a branch is a trap, so reject git's-/// reserved forms here.-fn valid_bookmark_name(name: bytes.Bytes) bool = trust {- if name.len == 0 || name.len > prim.MAX_NAME_LEN {- return false- }- val first: u8 = bytes.Bytes.at(name, 0)- if first == 45 || first == 47 || first == 46 {- return false- }- val last: u8 = bytes.Bytes.at(name, name.len - 1)- if last == 47 || last == 46 {- return false- }- val i: mut usize = 0- for i < name.len {- val c: u8 = bytes.Bytes.at(name, i)- if c == 0 || c == 32 || c < 32 || c == 127 {- return false- }- if c == 126 || c == 94 || c == 58 || c == 63 || c == 42 || c == 91 || c == 92 {- return false- }- i++- }- if contains_seq(name, bytes.bytes(c"..", 2)) {- return false- }- if contains_seq(name, bytes.bytes(c"@{", 2)) {- return false- }- if contains_seq(name, bytes.bytes(c"//", 2)) {- return false- }- if bytes.Bytes.eql(name, bytes.bytes(c"@", 1)) {- return false- }- val lock: bytes.Bytes = bytes.bytes(c".lock", 5)- if name.len >= lock.len- && bytes.Bytes.eql(bytes.Bytes.slice(name, name.len - lock.len, name.len), lock) {- return false- }- return true-}--fn make_description(prefix: bytes.Bytes, name: bytes.Bytes) bytes.Bytes = trust {- val b: mut buf.Buf = buf.new(prefix.len + 1 + name.len)- buf.Buf.put_bytes(b, prefix)- buf.Buf.put_u8(b, 32)- buf.Buf.put_bytes(b, name)- val out: bytes.Bytes = bytes.Bytes.dup(buf.Buf.view(b))- buf.Buf.free(b)- return out-}--fn short_commit(id: objid.Id, n: usize) str.StringView = trust {- val hex: ref u8 = objid.Id.hex(id)- val width: usize = 12- val mut_width: mut usize = width- if n > 0 {- mut_width = n- }- if mut_width > 64 {- mut_width = 64- }- val out: str.StringView = str.view(hex, mut_width as i64)- // The view is intentionally freed by the process at exit; callers only- // format it immediately.- return out-}--fn short_change(cid: objid.ChangeId) bytes.Bytes = trust {- val full: bytes.Bytes = changeid.encode(cid)- val n: usize = 8- val width: mut usize = n- if full.len < width {- width = full.len- }- val out: bytes.Bytes = dup_z(bytes.Bytes.slice(full, 0, width))- changeid.free(full)- return out-}--fn print_cell(text: str.StringView, width: usize) void = trust {- stdio.print("{s}", {text})- val pad: mut i64 = width as i64 - text.len- for pad > 0 {- stdio.print(" ", {})- pad--- }-}--fn run_set(repo: layout.Repo, args: list[ref u8], start: usize) i32 = trust {- val name: mut bytes.Bytes = bytes.empty()- val rev: mut bytes.Bytes = bytes.empty()- 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 && is_flag(a) {- msg.error_prefix()- stdio.eprint("unknown flag: {s}\n", {str.from_cstr(a)})- return 1- } else {- if name.len == 0 {- name = bytes.from_cstr(a)- } elif rev.len == 0 {- rev = bytes.from_cstr(a)- } else {- msg.error_prefix()- stdio.eprint("bmk set accepts a name and one revision\n", {})- return 1- }- }- }- i++- }- if name.len == 0 {- msg.error_prefix()- stdio.eprint("bmk set requires a name\n", {})- return 1- }- if !valid_bookmark_name(name) {- msg.error_prefix()- stdio.eprint(- "invalid bookmark name: {s}\n",- {str.view(name.ptr, name.len as i64)}- )- return 1- }-- 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 resolved = graph.resolve(st.handles, tx.view, rev)- val target: mut objid.Id = objid.id_none()- val mut_found: mut bool = false- if resolved is some id {- target = copy_id(id)- mut_found = true- }- if !mut_found {- msg.error_prefix()- if rev.len == 0 {- stdio.eprint("no working-copy commit\n", {})- } else {- stdio.eprint(- "unknown revision: {s}\n",- {str.view(rev.ptr, rev.len as i64)}- )- }- store.close(st)- txn.abort(tx)- return 1- }-- val existing = viewops.find_bookmark(tx.view, name)- val changed: mut bool = true- if existing is some idx {- val bmo = @get(tx.view.bookmarks, idx)- if bmo is some bm {- if viewops.bookmark_points_at(bm, target) {- changed = false- } else {- free_targets(bm.targets)- bm.targets.adds = lists.new[objid.Id]()- bm.targets.removes = lists.new[objid.Id]()- @append(bm.targets.adds, copy_id(target))- }- }- } else {- val bm: mut ref view.Bookmark = @alloc(@sizeof(view.Bookmark)) as ref view.Bookmark- bm.name = bytes.Bytes.dup(name)- bm.targets = view.empty_target_set()- @append(bm.targets.adds, copy_id(target))- @append(tx.view.bookmarks, bm)- viewops.sort_bookmarks(tx.view.bookmarks)- }-- if !changed {- val _ = repoconfig.set_current_bookmark(repo, name)- msg.info_prefix()- stdio.print(- "bookmark {s} is already at {s}\n",- {str.view(name.ptr, name.len as i64), short_commit(target, 0)}- )- store.close(st)- txn.abort(tx)- free_id(target)- return 0- }-- viewops.rebuild_heads(tx.view)- val description: bytes.Bytes = make_description(bytes.bytes(c"bookmark set", 12), name)- val status: i32 = txn.finish(tx, description)- if status == 0 {- val _ = repoconfig.set_current_bookmark(repo, name)- msg.info_prefix()- stdio.print(- "bookmark {s} set to {s}\n",- {str.view(name.ptr, name.len as i64), short_commit(target, 0)}- )- }- val dp: mut ref void = description.ptr as ref void- @free(dp)- store.close(st)- free_id(target)- return status-}--fn run_delete(repo: layout.Repo, args: list[ref u8], start: usize) i32 = trust {- val name: mut bytes.Bytes = bytes.empty()- 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)})- return 1- } else {- if name.len > 0 {- msg.error_prefix()- stdio.eprint("bmk rm accepts exactly one name\n", {})- return 1- }- name = bytes.from_cstr(a)- }- }- i++- }- if name.len == 0 {- msg.error_prefix()- stdio.eprint("bmk rm requires a name\n", {})- return 1- }-- 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 existing = viewops.find_bookmark(tx.view, name)- val idx: mut usize = 0- val mut_found: mut bool = false- if existing is some i2 {- idx = i2- mut_found = true- }- if !mut_found {- msg.error_prefix()- stdio.eprint(- "no such bookmark: {s}\n",- {str.view(name.ptr, name.len as i64)}- )- txn.abort(tx)- return 1- }- // The removed bookmark's name and target spans belong to the decoded view- // body; the process is short-lived, so simply drop the slot.- val _ = @remove(tx.view.bookmarks, idx)- viewops.rebuild_heads(tx.view)- val description: bytes.Bytes = make_description(bytes.bytes(c"bookmark delete", 15), name)- val status: i32 = txn.finish(tx, description)- if status == 0 {- val cur = repoconfig.current_bookmark(repo)- if cur is some cname {- if bytes.Bytes.eql(cname, name) {- val _ = repoconfig.clear_current_bookmark(repo)- }- bytes.free_owned(cname)- }- msg.info_prefix()- stdio.print("deleted bookmark {s}\n", {str.view(name.ptr, name.len as i64)})- }- val dp: mut ref void = description.ptr as ref void- @free(dp)- return status-}--fn run_list(repo: layout.Repo, args: list[ref u8], start: usize) i32 = trust {- 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"-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 {- msg.error_prefix()- stdio.eprint("bmk ls takes no operands\n", {})- return 1- }- }- i++- }- 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()- val have_wc: mut bool = false- if wc_opt is some id {- wc = id- have_wc = true- }- val w_commit: usize = 12- val w_change: usize = 8- val w_name: mut usize = 8- for bm in v.bookmarks {- if bm.name.len > w_name {- w_name = bm.name.len- }- }- if col_titles {- print_cell(str.from_cstr(c"Bookmark"), w_name)- stdio.print(" ", {})- print_cell(str.from_cstr(c"Commit"), w_commit)- stdio.print(" ", {})- print_cell(str.from_cstr(c"Change"), w_change)- stdio.print(" Target\n", {})- }- for bm in v.bookmarks {- val name_z: bytes.Bytes = dup_z(bm.name)- print_cell(str.view(name_z.ptr, name_z.len as i64), w_name)- stdio.print(" ", {})- val have_target: mut bool = false- val current: mut bool = false- val conflicted: bool = @len(bm.targets.adds) > 1- val commit_z: mut bytes.Bytes = bytes.empty()- val change_z: mut bytes.Bytes = bytes.empty()- if @len(bm.targets.adds) > 0 {- val first = @get(bm.targets.adds, 0)- if first is some tid {- have_target = true- if have_wc && objid.Id.eql(tid, wc) {- current = true- }- val short_c: str.StringView = short_commit(tid, 0)- commit_z = dup_z(bytes.bytes(short_c.ptr, short_c.len as usize))- val lc_opt = graph.load_commit(st.handles, tid)- if lc_opt is some lc {- change_z = short_change(lc.c.change_id)- graph.free_loaded(lc)- }- }- }- if !have_target {- print_cell(str.from_cstr(c"<missing>"), w_commit)- stdio.print(" ", {})- print_cell(str.from_cstr(c""), w_change)- stdio.print(" (missing)\n", {})- } else {- print_cell(str.view(commit_z.ptr, commit_z.len as i64), w_commit)- stdio.print(" ", {})- print_cell(str.view(change_z.ptr, change_z.len as i64), w_change)- stdio.print(" ", {})- if current {- terminal.print(str.from_cstr(c"@"), terminal.Color.Red)- }- if conflicted {- if current {- stdio.print(" ", {})- }- terminal.print(str.from_cstr(c"(conflicted)"), terminal.Color.BrightRed)- }- stdio.print("\n", {})- }- val np: mut ref void = name_z.ptr as ref void- @free(np)- if commit_z.ptr != none {- val cp: mut ref void = commit_z.ptr as ref void- @free(cp)- }- if change_z.ptr != none {- val chp: mut ref void = change_z.ptr as ref void- @free(chp)- }- }- if @len(v.bookmarks) == 0 {- msg.info_prefix()- stdio.print("no bookmarks\n", {})- }- if have_wc {- free_id(wc)- }- view.free_view(v)- store.close(st)- return 0-}--fn usage() void = trust {- stdio.puts("usage: vn bmk <set|mv|ls|rm> ...")- stdio.puts("")- stdio.puts("manage named, movable pointers to commits (branches)")- stdio.puts("")- stdio.puts("subcommands:")- stdio.puts(" set <name> [-rev <rev>] create or move a bookmark (default: @)")- stdio.puts(" mv <name> [-rev <rev>] alias of set")- stdio.puts(" ls [-no-col-titles] list bookmarks")- stdio.puts(" rm <name> delete a bookmark")-}--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 => {- usage()- return 1- }- }- if cmd_is(sub, c"set", 3) || cmd_is(sub, c"mv", 2) {- val repo_opt = layout.discover(str.from_cstr(c"."))- match repo_opt {- some repo => {- val status: i32 = run_set(repo, args, start + 1)- layout.free_repo(repo)- return status- }- none => {- msg.error_prefix()- stdio.eprint("not a veins repository\n", {})- return 1- }- }- }- if cmd_is(sub, c"ls", 2) {- val repo_opt = layout.discover(str.from_cstr(c"."))- match repo_opt {- some repo => {- val status: i32 = run_list(repo, args, start + 1)- layout.free_repo(repo)- return status- }- none => {- msg.error_prefix()- stdio.eprint("not a veins repository\n", {})- return 1- }- }- }- if cmd_is(sub, c"rm", 2) {- val repo_opt = layout.discover(str.from_cstr(c"."))- match repo_opt {- some repo => {- val status: i32 = run_delete(repo, args, start + 1)- layout.free_repo(repo)- return status- }- none => {- msg.error_prefix()- stdio.eprint("not a veins repository\n", {})- return 1- }- }- }- if cmd_is(sub, c"help", 4) || cmd_is(sub, c"-h", 2) {- usage()- return 0- }- msg.error_prefix()- stdio.eprint("unknown bmk subcommand: {s}\n", {str.from_cstr(sub)})- usage()- return 1-}--- a/veins/src/cli/cfg_cmd.sx+++ /dev/null@@ -1,420 +0,0 @@-/// `vn cfg`: read and write local repository or user configuration.--val stdio = use("std/stdio")-val str = use("std/string")-val bytes = use("../core/bytes.sx")-val lists = use("../core/lists.sx")-val prim = use("../core/primitives.sx")-val msg = use("../core/msg.sx")-val files = use("../io/files.sx")-val layout = use("../store/layout.sx")-val repoconfig = use("../core/repoconfig.sx")-val userconfig = use("../core/userconfig.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 is_flag(a: ref u8) bool = trust {- if a == none {- return false- }- if @strlen(a) == 0 {- return false- }- return @load8(a) == 45-}--fn cmd_is(a: ref u8, text: ref u8, len: usize) bool = trust {- return bytes.Bytes.eql(bytes.from_cstr(a), bytes.bytes(text, len))-}--fn bytes_is(b: bytes.Bytes, text: ref u8, len: usize) bool = trust {- return bytes.Bytes.eql(b, bytes.bytes(text, len))-}--fn free_entries(entries: list[ref prim.KeyValue]) void = trust {- for kv in entries {- 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 ep: mut ref void = kv as ref void- @free(ep)- }- @listfree(entries)-}--fn sort_entries(entries: mut list[ref prim.KeyValue]) void = trust {- val n: usize = @len(entries)- val i: mut usize = 1- for i < n {- val cur = @get(entries, i)- val c: mut ref prim.KeyValue = none- if cur is some v {- c = v- }- val j: mut usize = i- for j > 0 {- val prev_opt = @get(entries, j - 1)- val prev: mut ref prim.KeyValue = none- if prev_opt is some p {- prev = p- }- if bytes.Bytes.cmp(prev.key, c.key) <= 0 {- break- }- @set(entries, j, prev)- j--- }- @set(entries, j, c)- i++- }-}--fn repo_entries(repo: layout.Repo) list[ref prim.KeyValue] = trust {- val entries: mut list[ref prim.KeyValue] = lists.new[ref prim.KeyValue]()- 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 {- eq = i as i64- break- }- i++- }- if eq >= 0 {- val key: bytes.Bytes = trim(- bytes.Bytes.slice(line, 0, eq as usize)- )- if key.len > 0 {- val value: bytes.Bytes = trim(- bytes.Bytes.slice(- line,- eq as usize + 1,- line.len- )- )- val kv: mut ref prim.KeyValue = @alloc(- @sizeof(prim.KeyValue)- ) as ref prim.KeyValue- kv.key = bytes.Bytes.dup(key)- kv.value = bytes.Bytes.dup(value)- @append(entries, kv)- }- }- }- start = pos + 1- }- pos++- }- files.free_buffer(data)- }- sort_entries(entries)- return entries-}--fn print_entry(key: bytes.Bytes, value: bytes.Bytes) void = trust {- stdio.print(- "{s} = {s}\n",- {str.view(key.ptr, key.len as i64), str.view(value.ptr, value.len as i64)}- )-}--fn cfg_list(root: layout.Repo, global: bool) i32 = trust {- if global {- val email = userconfig.author_email()- if email is some v {- print_entry(bytes.bytes(c"user.email", 10), v)- bytes.free_owned(v)- }- val name = userconfig.author_name()- if name is some v {- print_entry(bytes.bytes(c"user.name", 9), v)- bytes.free_owned(v)- }- return 0- }- val entries = repo_entries(root)- for kv in entries {- print_entry(kv.key, kv.value)- }- free_entries(entries)- return 0-}--fn cfg_get(root: layout.Repo, global: bool, key: bytes.Bytes) i32 = trust {- val value: mut option[bytes.Bytes] = none- if global {- if bytes_is(key, c"user.name", 9) {- value = userconfig.author_name()- } elif bytes_is(key, c"user.email", 10) {- value = userconfig.author_email()- }- } else {- value = repoconfig.get(root, key)- }- match value {- some v => {- stdio.print("{s}\n", {str.view(v.ptr, v.len as i64)})- bytes.free_owned(v)- return 0- }- none => {- msg.error_prefix()- stdio.eprint("unknown config key: {s}\n", {str.view(key.ptr, key.len as i64)})- return 1- }- }-}--fn cfg_set(root: layout.Repo, global: bool, key: bytes.Bytes, value: bytes.Bytes) i32 = trust {- if global {- if !userconfig.set(key, value) {- msg.error_prefix()- stdio.eprint("cannot write user config\n", {})- return 1- }- return 0- }- if !repoconfig.set(root, key, value) {- msg.error_prefix()- stdio.eprint("cannot write repository config\n", {})- return 1- }- return 0-}--fn cfg_unset(root: layout.Repo, global: bool, key: bytes.Bytes) i32 = trust {- if global {- if !userconfig.remove(key) {- msg.error_prefix()- stdio.eprint("cannot write user config\n", {})- return 1- }- return 0- }- if !repoconfig.remove(root, key) {- msg.error_prefix()- stdio.eprint("cannot write repository config\n", {})- return 1- }- return 0-}--fn usage() void = trust {- stdio.puts("usage: vn cfg [<key>] [<value>]")- stdio.puts(" vn cfg [<get|set|unset|list>] [<key>] [<value>]")- stdio.puts(" vn cfg -list")- stdio.puts(" vn cfg -unset <key>")- stdio.puts("")- stdio.puts("read and write local repository configuration")- stdio.puts("")- stdio.puts(" vn cfg list all keys")- stdio.puts(" vn cfg <key> print a value")- stdio.puts(" vn cfg <key> <value> set a value")- stdio.puts(" vn cfg -unset <key> remove a key")- stdio.puts(" vn cfg -global ... use the user config instead")-}--pub fn run(args: list[ref u8], start: usize) i32 = trust {- val first_opt = @get(args, start)- if first_opt is some first {- if cmd_is(first, c"help", 4) || cmd_is(first, c"-h", 2)- || cmd_is(first, c"--help", 6) {- usage()- return 0- }- }- val global: mut bool = false- val list: mut bool = false- val unset: mut bool = false- val end_flags: mut bool = false- val positional: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()- 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"-global", 7) || cmd_is(a, c"--global", 8)- || cmd_is(a, c"-g", 2)) {- global = true- } elif !end_flags- && (cmd_is(a, c"-list", 5) || cmd_is(a, c"--list", 6)- || cmd_is(a, c"-l", 2)) {- list = true- } elif !end_flags && (cmd_is(a, c"-unset", 6) || cmd_is(a, c"--unset", 7)) {- unset = true- } elif !end_flags && is_flag(a) {- msg.error_prefix()- stdio.eprint("unknown flag: {s}\n", {str.from_cstr(a)})- @listfree(positional)- return 1- } else {- @append(positional, bytes.from_cstr(a))- }- }- i++- }-- if @len(positional) == 1 {- val first = @get(positional, 0)- if first is some key {- if bytes_is(key, c"list", 4) || bytes_is(key, c"ls", 2) {- list = true- @listfree(positional)- positional = lists.new[bytes.Bytes]()- }- }- }- if @len(positional) == 2 {- val first = @get(positional, 0)- if first is some key {- if bytes_is(key, c"get", 3) {- val second = @get(positional, 1)- @listfree(positional)- positional = lists.new[bytes.Bytes]()- if second is some k {- @append(positional, k)- }- } elif bytes_is(key, c"unset", 5) || bytes_is(key, c"rm", 2)- || bytes_is(key, c"remove", 6) {- unset = true- val second = @get(positional, 1)- @listfree(positional)- positional = lists.new[bytes.Bytes]()- if second is some k {- @append(positional, k)- }- }- }- }- if @len(positional) == 3 {- val first = @get(positional, 0)- if first is some key {- if bytes_is(key, c"set", 3) {- val second = @get(positional, 1)- val third = @get(positional, 2)- @listfree(positional)- positional = lists.new[bytes.Bytes]()- if second is some k {- @append(positional, k)- }- if third is some v {- @append(positional, v)- }- }- }- }-- if list {- if @len(positional) != 0 {- msg.error_prefix()- stdio.eprint("cfg list takes no operands\n", {})- @listfree(positional)- return 1- }- } elif unset {- if @len(positional) != 1 {- msg.error_prefix()- stdio.eprint("cfg unset requires one key\n", {})- @listfree(positional)- return 1- }- } elif @len(positional) > 2 {- msg.error_prefix()- stdio.eprint("cfg accepts a key and one value\n", {})- @listfree(positional)- return 1- }-- val repo: mut layout.Repo = layout.Repo{root: bytes.empty()}- val have_repo: mut bool = false- if !global {- val repo_opt = layout.discover(str.from_cstr(c"."))- match repo_opt {- some r => {- repo = r- have_repo = true- }- none => {- msg.error_prefix()- stdio.eprint("not a veins repository\n", {})- @listfree(positional)- return 1- }- }- }-- val status: mut i32 = 0- if list || @len(positional) == 0 {- status = cfg_list(repo, global)- } elif unset {- val key_opt = @get(positional, 0)- val key: mut bytes.Bytes = bytes.empty()- if key_opt is some k {- key = k- }- status = cfg_unset(repo, global, key)- } elif @len(positional) == 1 {- val key_opt = @get(positional, 0)- val key: mut bytes.Bytes = bytes.empty()- if key_opt is some k {- key = k- }- status = cfg_get(repo, global, key)- } else {- val key_opt = @get(positional, 0)- val value_opt = @get(positional, 1)- val key: mut bytes.Bytes = bytes.empty()- val value: mut bytes.Bytes = bytes.empty()- if key_opt is some k {- key = k- }- if value_opt is some v {- value = v- }- status = cfg_set(repo, global, key, value)- }-- if have_repo {- layout.free_repo(repo)- }- @listfree(positional)- return status-}--- a/veins/src/cli/checkout_cmd.sx+++ /dev/null@@ -1,32 +0,0 @@-/// `vn co [rev]` (alias `vn checkout`): 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/veins/src/cli/clone_cmd.sx+++ /dev/null@@ -1,293 +0,0 @@-/// `vn clone`: fetch a repository over the native protocol.--val stdio = use("std/stdio")-val str = use("std/string")-val bytes = use("../core/bytes.sx")-val lists = use("../core/lists.sx")-val objid = use("../object/id.sx")-val store = use("../store/store.sx")-val layout = use("../store/layout.sx")-val files = use("../io/files.sx")-val config = use("../core/repoconfig.sx")-val remote_config = use("../git/remote.sx")-val credentials = use("../auth/credentials.sx")-val client = use("../protocol/client.sx")-val msg_refs = use("../protocol/messages.sx")-val transfer = use("../protocol/transfer.sx")-val promisor = use("../protocol/promisor.sx")-val checkout = use("../worktree/checkout.sx")-val cmsg = use("../core/msg.sx")--fn last_segment(path: bytes.Bytes) bytes.Bytes = trust {- val slash: mut i64 = -1- val i: mut usize = 0- for i < path.len {- if bytes.Bytes.at(path, i) == 47 {- slash = i as i64- }- i++- }- if slash >= 0 && (slash as usize) + 1 < path.len {- return bytes.Bytes.slice(path, (slash as usize) + 1, path.len)- }- if path.len > 0 {- return path- }- return bytes.bytes(c"repo", 4)-}--fn selected_commits(- refs: list[msg_refs.RefInfo],- policy: bytes.Bytes-) list[objid.Id] = trust {- val out: mut list[objid.Id] = lists.new[objid.Id]()- if bytes.Bytes.eql(policy, bytes.bytes(c"none", 4)) {- return out- }- if bytes.Bytes.eql(policy, bytes.bytes(c"head", 4)) {- val dt = transfer.default_target(refs)- if dt is some id {- @append(out, id)- }- return out- }- for r in refs {- if r.target.ptr != none {- @append(out, objid.id(r.target.ptr))- }- }- return out-}--fn send_chunks(c: mut ref client.Client, repo: layout.Repo, all: list[bytes.Bytes]) bool = trust {- val n: usize = @len(all)- val off: mut usize = 0- for off < n {- val batch: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()- val end: usize = off + 4096- val lim: mut usize = n- if end < n {- lim = end- }- val i: mut usize = off- for i < lim {- val o = @get(all, i)- if o is some v {- @append(batch, v)- }- i++- }- if !client.get_chunks(c, repo, batch) {- @listfree(batch)- return false- }- @listfree(batch)- off = lim- }- return true-}--fn report_client_error(c: ref client.Client, context: bytes.Bytes) void = trust {- val detail: bytes.Bytes = client.error_text(c)- cmsg.error_prefix()- if detail.len > 0 {- stdio.eprint("{s}: {s}\n", {- str.view(context.ptr, context.len as i64),- str.view(detail.ptr, detail.len as i64)- })- } else {- stdio.eprint("{s}\n", {str.view(context.ptr, context.len as i64)})- }- bytes.free_owned(detail)-}--pub fn run(args: list[ref u8], start: usize) i32 = trust {- val url: mut bytes.Bytes = bytes.empty()- val path: mut bytes.Bytes = bytes.empty()- val policy: mut bytes.Bytes = bytes.bytes(c"head", 4)- val key_name: mut bytes.Bytes = bytes.empty()- val key_explicit: mut bool = false- val tls_pin: mut bytes.Bytes = bytes.empty()- 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)- if bytes.Bytes.starts_with(av, bytes.bytes(c"-blobs:", 7)) {- policy = bytes.Bytes.dup(bytes.Bytes.slice(av, 7, av.len))- } elif bytes.Bytes.starts_with(av, bytes.bytes(c"-key:", 5)) {- key_name = bytes.Bytes.dup(bytes.Bytes.slice(av, 5, av.len))- if bytes.Bytes.starts_with(key_name, bytes.bytes(c"ed25519:", 8)) {- cmsg.error_prefix()- stdio.eprint("-key: expects a local key name, not a public key\n", {})- return 1- }- key_explicit = true- } elif bytes.Bytes.starts_with(av, bytes.bytes(c"-pin:", 5)) {- tls_pin = bytes.Bytes.dup(bytes.Bytes.slice(av, 5, av.len))- } elif av.len > 0 && bytes.Bytes.at(av, 0) == 45 {- cmsg.error_prefix()- stdio.eprint("unknown flag: {s}\n", {str.from_cstr(a)})- return 1- } elif url.ptr == none {- url = bytes.Bytes.dup(av)- } else {- path = bytes.Bytes.dup(av)- }- }- i++- }- if url.ptr == none {- cmsg.error_prefix()- stdio.eprint("clone requires a URL\n", {})- return 1- }- if path.ptr == none {- path = bytes.Bytes.dup(last_segment(url))- }- val purl = client.parse_url(url)- if purl is none {- cmsg.error_prefix()- stdio.eprint("unsupported URL\n", {})- return 1- }- val pv: bytes.Bytes = path- val repo_r = layout.init(files.to_view(pv))- val repo: mut layout.Repo = layout.Repo{root: bytes.empty()}- match repo_r {- ok r => {- repo = r- }- err e => {- cmsg.error_prefix()- stdio.eprint("cannot create repository ({d})\n", {e})- return 1- }- }- if key_name.ptr == none {- val fallback = credentials.key_for_url(url)- if fallback is some ck {- key_name = ck- }- }- val remote_name: bytes.Bytes = bytes.Bytes.dup(bytes.bytes(c"origin", 6))- val url_key: bytes.Bytes = remote_config.key_for(remote_name, bytes.bytes(c"url", 3))- config.set(repo, url_key, url)- bytes.free_owned(url_key)- if key_explicit && key_name.ptr != none {- val remote_key: bytes.Bytes = remote_config.key_for(remote_name, bytes.bytes(c"key", 3))- config.set(repo, remote_key, key_name)- bytes.free_owned(remote_key)- }- if tls_pin.len > 0 {- val pk: bytes.Bytes = remote_config.key_for(remote_name, bytes.bytes(c"tls-pin", 7))- config.set(repo, pk, tls_pin)- bytes.free_owned(pk)- }- val repo_name: bytes.Bytes = client.url_repo_name(url)- val c_opt = client.connect_pinned(url, key_name, repo_name, tls_pin)- val c: mut ref client.Client = none- match c_opt {- some v => {- c = v- }- none => {- val detail: bytes.Bytes = client.last_connect_error()- cmsg.error_prefix()- if detail.len > 0 {- stdio.eprint("{s}\n", {str.view(detail.ptr, detail.len as i64)})- } else {- stdio.eprint("cannot connect or authenticate\n", {})- }- bytes.free_owned(detail)- layout.free_repo(repo)- return 1- }- }- val refs_opt = client.list_refs(c)- if refs_opt is none {- report_client_error(c, bytes.bytes(c"cannot list remote refs", 23))- client.free_client(c)- layout.free_repo(repo)- return 1- }- val refs: mut list[msg_refs.RefInfo] = lists.new[msg_refs.RefInfo]()- match refs_opt {- some rv => {- refs = rv- }- none => {- return 1- }- }- val wants: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()- for r in refs {- if r.target.ptr != none {- @append(wants, bytes.Bytes.dup(bytes.bytes(r.target.ptr, 32)))- }- }- if @len(wants) == 0 {- @listfree(wants)- client.free_client(c)- cmsg.info_prefix()- stdio.print("cloned empty repository into {s}\n", {str.view(pv.ptr, pv.len as i64)})- layout.free_repo(repo)- return 0- }- val haves: list[bytes.Bytes] = lists.new[bytes.Bytes]()- if !client.negotiate(c, wants, haves) {- report_client_error(c, bytes.bytes(c"negotiation failed", 18))- @listfree(haves)- transfer.free_id_bytes(wants)- client.free_client(c)- layout.free_repo(repo)- return 1- }- @listfree(haves)- if !client.fetch_skeleton(c, repo, wants) {- report_client_error(c, bytes.bytes(c"fetch failed", 12))- transfer.free_id_bytes(wants)- client.free_client(c)- layout.free_repo(repo)- return 1- }- transfer.free_id_bytes(wants)- val st: store.Store = store.open_all(repo)- val commits: list[objid.Id] = selected_commits(refs, policy)- val chunks: list[bytes.Bytes] = transfer.chunks_for_commits(st.handles, commits)- @listfree(commits)- val chunks_ok: bool = send_chunks(c, repo, chunks)- transfer.free_id_bytes(chunks)- store.close(st)- if !chunks_ok {- report_client_error(c, bytes.bytes(c"chunk fetch failed", 18))- client.free_client(c)- layout.free_repo(repo)- return 1- }- val applied: i32 = transfer.apply_refs(repo, refs, remote_name, true)- if applied != 0 {- cmsg.error_prefix()- stdio.eprint("cannot write repository state\n", {})- client.free_client(c)- layout.free_repo(repo)- return 1- }- val prom_key: bytes.Bytes = bytes.bytes(c"promisor", 8)- config.set(repo, prom_key, remote_name)- promisor.configure(repo, remote_name)- if bytes.Bytes.eql(policy, bytes.bytes(c"none", 4)) {- cmsg.info_prefix()- stdio.print("cloned metadata only; blobs are promised\n", {})- }- val co: i32 = checkout.materialize_working_copy(repo)- if co != 0 {- cmsg.info_prefix()- stdio.print("cloned; checkout reported {d}\n", {co})- }- cmsg.info_prefix()- stdio.print("cloned into {s}\n", {str.view(pv.ptr, pv.len as i64)})- client.free_client(c)- layout.free_repo(repo)- return 0-}--- a/veins/src/cli/diff_cmd.sx+++ /dev/null@@ -1,501 +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 terminal = use("std/terminal")-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")--val OP_CONTEXT: u8 = 32-val OP_ADD: u8 = 43-val OP_DEL: u8 = 45--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)- val g: mut GitSource = GitSource{repo: @zeroed, open: false}- match r {- ok x => {- // object.open takes ownership of the path on success.- g.repo = x- g.open = true- }- err _ => {- files.free_path(p)- }- }- 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 new_op(tag: u8, ai: usize, bi: usize) ref DiffOp = trust {- val op: mut ref DiffOp = @alloc(@sizeof(DiffOp)) as ref DiffOp- op.tag = tag- op.ai = ai- op.bi = bi- return op-}--fn free_ops(ops: list[ref DiffOp]) void = trust {- for op in ops {- val p: mut ref void = op as ref void- @free(p)- }- @listfree(ops)-}--fn op_at(ops: list[ref DiffOp], i: usize) ref DiffOp = trust {- val o = @get(ops, i)- if o is some op {- return op- }- assert false- return none-}--fn reverse_ops(ops: mut list[ref DiffOp]) void = trust {- val n: usize = @len(ops)- val i: mut usize = 0- for i < n / 2 {- val a: ref DiffOp = op_at(ops, i)- val b: ref DiffOp = op_at(ops, n - 1 - i)- @set(ops, i, b)- @set(ops, n - 1 - i, a)- i++- }-}--fn lcs_get(dp: ref u32, idx: usize) u32 = trust {- val p: ref u32 = @ptradd(dp as ref void, (idx * 4) as i64) as ref u32- return @load32(p) as u32-}--fn lcs_set(dp: ref u32, idx: usize, value: u32) void = trust {- val p: ref u32 = @ptradd(dp as ref void, (idx * 4) as i64) as ref u32- @store32(p, value as i32)-}--fn build_ops(a: list[bytes.Bytes], b: list[bytes.Bytes]) list[ref DiffOp] = trust {- val n: usize = @len(a)- val m: usize = @len(b)- val cols: usize = m + 1- val cells: usize = (n + 1) * cols- val dp: ref u32 = @alloc(cells * 4) as ref u32- @memset(dp as ref void, 0, cells * 4)- val i: mut usize = 1- for i <= n {- val j: mut usize = 1- for j <= m {- if bytes.Bytes.eql(line_at(a, i - 1), line_at(b, j - 1)) {- lcs_set(dp, i * cols + j, lcs_get(dp, (i - 1) * cols + (j - 1)) + 1)- } else {- val up: u32 = lcs_get(dp, (i - 1) * cols + j)- val left: u32 = lcs_get(dp, i * cols + (j - 1))- val best: mut u32 = left- if up > best {- best = up- }- lcs_set(dp, i * cols + j, best)- }- j++- }- i++- }- val ops: mut list[ref DiffOp] = lists.new[ref DiffOp]()- val oi: mut usize = n- val oj: mut usize = m- for oi > 0 || oj > 0 {- if oi > 0 && oj > 0 && bytes.Bytes.eql(line_at(a, oi - 1), line_at(b, oj - 1)) {- @append(ops, new_op(OP_CONTEXT, oi - 1, oj - 1))- oi--- oj--- } elif oj > 0- && (oi == 0 || lcs_get(dp, oi * cols + (oj - 1)) >= lcs_get(dp, (oi - 1) * cols + oj)) {- @append(ops, new_op(OP_ADD, 0, oj - 1))- oj--- } else {- @append(ops, new_op(OP_DEL, oi - 1, 0))- oi--- }- }- reverse_ops(ops)- @free(dp as ref void)- return ops-}--fn change_at(xs: list[usize], i: usize) usize = trust {- val o = @get(xs, i)- if o is some v {- return v- }- return 0-}--fn render_unified(a: list[bytes.Bytes], b: list[bytes.Bytes]) void = trust {- val ops: list[ref DiffOp] = build_ops(a, b)- val nops: usize = @len(ops)- val changes: mut list[usize] = lists.new[usize]()- val k: mut usize = 0- for k < nops {- val op: ref DiffOp = op_at(ops, k)- if op.tag != OP_CONTEXT {- @append(changes, k)- }- k++- }- val context: usize = 3- val pos: mut usize = 0- val old_seen: mut usize = 0- val new_seen: mut usize = 0- val ci: mut usize = 0- for ci < @len(changes) {- val first: usize = change_at(changes, ci)- val start: mut usize = 0- if first > context {- start = first - context- }- val last: mut usize = first- ci++- for ci < @len(changes) {- val c: usize = change_at(changes, ci)- if c > last + context * 2 {- break- }- last = c- ci++- }- val end: mut usize = last + context + 1- if end > nops {- end = nops- }- for pos < start {- val skip: ref DiffOp = op_at(ops, pos)- if skip.tag == OP_CONTEXT {- old_seen++- new_seen++- } elif skip.tag == OP_DEL {- old_seen++- } else {- new_seen++- }- pos++- }- val old_count: mut usize = 0- val new_count: mut usize = 0- val e: mut usize = start- for e < end {- val op: ref DiffOp = op_at(ops, e)- if op.tag == OP_CONTEXT {- old_count++- new_count++- } elif op.tag == OP_DEL {- old_count++- } else {- new_count++- }- e++- }- val old_start: mut usize = old_seen- if old_count > 0 {- old_start++- }- val new_start: mut usize = new_seen- if new_count > 0 {- new_start++- }- stdio.print(- "@@ -{d},{d} +{d},{d} @@\n",- {old_start, old_count, new_start, new_count}- )- for pos < end {- val op: ref DiffOp = op_at(ops, pos)- if op.tag == OP_CONTEXT {- val line: bytes.Bytes = line_at(a, op.ai)- stdio.print(" {s}\n", {str.view(line.ptr, line.len as i64)})- old_seen++- new_seen++- } elif op.tag == OP_DEL {- val line: bytes.Bytes = line_at(a, op.ai)- terminal.print(str.from_cstr(c"-"), terminal.Color.Red)- terminal.print(str.view(line.ptr, line.len as i64), terminal.Color.Red)- stdio.print("\n", {})- old_seen++- } else {- val line: bytes.Bytes = line_at(b, op.bi)- terminal.print(str.from_cstr(c"+"), terminal.Color.Green)- terminal.print(str.view(line.ptr, line.len as i64), terminal.Color.Green)- stdio.print("\n", {})- new_seen++- }- pos++- }- }- @listfree(changes)- free_ops(ops)-}--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 {- terminal.print(str.from_cstr(c"--- "), terminal.Color.Red)- if change.old_kind == treewalk.KIND_MISSING {- terminal.print(str.from_cstr(c"/dev/null"), terminal.Color.Red)- } else {- terminal.print(str.from_cstr(c"a/"), terminal.Color.Red)- terminal.print(path_view, terminal.Color.Red)- }- stdio.print("\n", {})- terminal.print(str.from_cstr(c"+++ "), terminal.Color.Green)- if change.new_kind == treewalk.KIND_MISSING {- terminal.print(str.from_cstr(c"/dev/null"), terminal.Color.Green)- } else {- terminal.print(str.from_cstr(c"b/"), terminal.Color.Green)- terminal.print(path_view, terminal.Color.Green)- }- stdio.print("\n", {})- val a = split_lines(old_data)- val b = split_lines(new_data)- render_unified(a, b)- @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]-) usize = trust {- val changes = treediff.compare(handles, old_tree, new_tree)- val count: usize = @len(changes)- for c in changes {- render_one(handles, git, c)- }- treediff.free(changes)- return count-}--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)- val count: usize = render(st.handles, git, old_tree, new_tree)- close_git(git)- if count == 0 {- msg.info_prefix()- stdio.print("no diff to show\n", {})- }- }- 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/veins/src/cli/ex_cmd.sx+++ /dev/null@@ -1,254 +0,0 @@-/// `vn ex <pattern>...`: append ignore patterns to the repository's-/// root `.vnexclude` file.-///-/// Patterns use gitignore-style syntax. Shell users should quote patterns that-/// contain wildcards (`vn ex '*.dSYM'`) so the shell does not expand them into-/// individual file names first.--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 names = use("../object/names.sx")-val layout = use("../store/layout.sx")-val pathspec = use("../worktree/pathspec.sx")-val files = use("../io/files.sx")--fn cmd_is(a: ref u8, text: ref u8, len: usize) bool = trust {- 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 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 line_exists(data: bytes.Bytes, pattern: bytes.Bytes) bool = trust {- if data.len == 0 {- return false- }- 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 bytes.Bytes.eql(line, pattern) {- return true- }- start = pos + 1- }- pos++- }- return false-}--fn contains_pattern(xs: list[bytes.Bytes], pattern: bytes.Bytes) bool = trust {- for p in xs {- if bytes.Bytes.eql(p, pattern) {- return true- }- }- return false-}--fn free_paths(xs: list[bytes.Bytes]) void = trust {- for p in xs {- if p.ptr != none {- val pp: mut ref void = p.ptr as ref void- @free(pp)- }- }- @listfree(xs)-}--pub fn run(args: list[ref u8], start: usize) i32 = trust {- val operands: mut list[ref u8] = lists.new[ref u8]()- 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(operands)- return 1- } else {- @append(operands, a)- }- }- i++- }- if @len(operands) == 0 {- msg.error_prefix()- stdio.eprint("ex requires at least one pattern\n", {})- @listfree(operands)- return 1- }-- val repo_opt = layout.discover(str.from_cstr(c"."))- 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\n", {})- @listfree(operands)- return 1- }- }-- val cwd_opt = pathspec.cwd_relative(repo.root)- val cwd_rel: mut bytes.Bytes = bytes.empty()- match cwd_opt {- some c => {- cwd_rel = c- }- none => {- msg.error_prefix()- stdio.eprint("cannot determine current directory\n", {})- @listfree(operands)- layout.free_repo(repo)- return 1- }- }-- val patterns: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()- val bad: mut bool = false- for a in operands {- val arg: bytes.Bytes = bytes.from_cstr(a)- val norm_opt = pathspec.normalize(repo.root, cwd_rel, arg)- val norm: mut bytes.Bytes = bytes.empty()- match norm_opt {- some n => {- norm = n- }- none => {- msg.error_prefix()- stdio.eprint(- "pattern is outside the repository: {s}\n",- {str.view(arg.ptr, arg.len as i64)}- )- bad = true- }- }- if bad {- if norm.ptr != none {- val np: mut ref void = norm.ptr as ref void- @free(np)- }- break- }- if norm.len == 0 || !names.valid_path(norm) {- msg.error_prefix()- stdio.eprint("{s}\n", {str.view(arg.ptr, arg.len as i64)})- stdio.eprint("not a valid exclude pattern\n", {})- if norm.ptr != none {- val np2: mut ref void = norm.ptr as ref void- @free(np2)- }- bad = true- break- }- @append(patterns, norm)- }- if bad {- if cwd_rel.ptr != none {- val cp: mut ref void = cwd_rel.ptr as ref void- @free(cp)- }- free_paths(patterns)- @listfree(operands)- layout.free_repo(repo)- return 1- }-- val exclude_path: str.StringView = files.join(- layout.root_view(repo),- str.from_cstr(c".vnexclude")- )- val data_opt = files.read_all(exclude_path)- val data: mut bytes.Bytes = bytes.empty()- if data_opt is some d {- data = d- }-- val additions: mut buf.Buf = buf.new(64)- val added: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()- for pattern in patterns {- if !line_exists(data, pattern) && !contains_pattern(added, pattern) {- if buf.Buf.view(additions).len == 0 && data.len > 0 {- if bytes.Bytes.at(data, data.len - 1) != 10 {- buf.Buf.put_u8(additions, 10)- }- }- @append(added, pattern)- buf.Buf.put_bytes(additions, pattern)- buf.Buf.put_u8(additions, 10)- }- }-- val count: usize = @len(added)- val status: mut i32 = 0- if count == 0 {- msg.info_prefix()- stdio.print("no new exclude rules\n", {})- } else {- val wrote: bool = files.append_all(exclude_path, buf.Buf.view(additions))- if !wrote {- msg.error_prefix()- stdio.eprint("cannot write .vnexclude\n", {})- status = 1- } else {- msg.info_prefix()- stdio.print("added {d} exclude rule(s)\n", {count})- }- }-- buf.Buf.free(additions)- @listfree(added)- if data.ptr != none {- files.free_buffer(data)- }- files.free_path(exclude_path)- if cwd_rel.ptr != none {- val cp2: mut ref void = cwd_rel.ptr as ref void- @free(cp2)- }- free_paths(patterns)- @listfree(operands)- layout.free_repo(repo)- return status-}--- a/veins/src/cli/fetch_cmd.sx+++ /dev/null@@ -1,286 +0,0 @@-/// `vn fetch`: native incremental fetch.--val stdio = use("std/stdio")-val str = use("std/string")-val bytes = use("../core/bytes.sx")-val lists = use("../core/lists.sx")-val objid = use("../object/id.sx")-val store = use("../store/store.sx")-val state = use("../store/state.sx")-val layout = use("../store/layout.sx")-val remote_config = use("../git/remote.sx")-val credentials = use("../auth/credentials.sx")-val client = use("../protocol/client.sx")-val transfer = use("../protocol/transfer.sx")-val msg_refs = use("../protocol/messages.sx")-val cmsg = use("../core/msg.sx")--fn send_chunks(c: mut ref client.Client, repo: layout.Repo, all: list[bytes.Bytes]) bool = trust {- val st: store.Store = store.open_all(repo)- val missing: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()- for x in all {- val loc: mut store.Loc = store.Loc{pack_index: 0, record_index: 0, kind: 0}- if !store.find_handles(st.handles, objid.id(x.ptr), loc) {- @append(missing, x)- }- }- store.close(st)- val n: usize = @len(missing)- val off: mut usize = 0- for off < n {- val batch: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()- val end: usize = off + 4096- val lim: mut usize = n- if end < n {- lim = end- }- val i: mut usize = off- for i < lim {- val o = @get(missing, i)- if o is some v {- @append(batch, v)- }- i++- }- if !client.get_chunks(c, repo, batch) {- @listfree(batch)- @listfree(missing)- return false- }- @listfree(batch)- off = lim- }- @listfree(missing)- return true-}--fn report_client_error(c: ref client.Client, context: bytes.Bytes) void = trust {- val detail: bytes.Bytes = client.error_text(c)- cmsg.error_prefix()- if detail.len > 0 {- stdio.eprint("{s}: {s}\n", {- str.view(context.ptr, context.len as i64),- str.view(detail.ptr, detail.len as i64)- })- } else {- stdio.eprint("{s}\n", {str.view(context.ptr, context.len as i64)})- }- bytes.free_owned(detail)-}--pub fn run(args: list[ref u8], start: usize) i32 = trust {- val remote_name: mut bytes.Bytes = bytes.Bytes.dup(bytes.bytes(c"origin", 6))- val path: mut str.StringView = str.from_cstr(c".")- val explicit_key: mut bytes.Bytes = bytes.empty()- val explicit_pin: mut bytes.Bytes = bytes.empty()- val have_remote: mut bool = false- 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)- if bytes.Bytes.starts_with(av, bytes.bytes(c"-key:", 5)) {- explicit_key = bytes.Bytes.dup(bytes.Bytes.slice(av, 5, av.len))- if bytes.Bytes.starts_with(explicit_key, bytes.bytes(c"ed25519:", 8)) {- cmsg.error_prefix()- stdio.eprint("-key: expects a local key name, not a public key\n", {})- return 1- }- } elif bytes.Bytes.starts_with(av, bytes.bytes(c"-pin:", 5)) {- explicit_pin = bytes.Bytes.dup(bytes.Bytes.slice(av, 5, av.len))- } elif av.len > 0 && bytes.Bytes.at(av, 0) == 45 {- cmsg.error_prefix()- stdio.eprint("unknown flag: {s}\n", {str.from_cstr(a)})- return 1- } elif !have_remote {- remote_name = bytes.Bytes.dup(av)- have_remote = true- } else {- path = str.from_cstr(a)- }- }- i++- }- val repo_opt = layout.discover(path)- val repo: mut layout.Repo = layout.Repo{root: bytes.empty()}- match repo_opt {- some r => {- repo = r- }- none => {- cmsg.error_prefix()- stdio.eprint("not a veins repository\n", {})- return 1- }- }- val url_opt = remote_config.url_of(repo, remote_name)- if url_opt is none {- cmsg.error_prefix()- stdio.eprint("unknown remote\n", {})- layout.free_repo(repo)- return 1- }- val url: mut bytes.Bytes = bytes.empty()- match url_opt {- some v => {- url = v- }- none => {- return 1- }- }- val key_name = remote_config.key_name_of(repo, remote_name)- val key: mut bytes.Bytes = bytes.empty()- if explicit_key.ptr != none {- key = explicit_key- } else {- if key_name is some k {- if credentials.local_key_exists(k) {- key = k- } else {- bytes.free_owned(k)- }- }- if key.ptr == none {- val fallback = credentials.key_for_url(url)- if fallback is some ck {- key = ck- }- }- }- val pin_opt = remote_config.tls_pin_of(repo, remote_name)- val pin: mut bytes.Bytes = bytes.empty()- if explicit_pin.ptr != none {- pin = explicit_pin- } else {- if pin_opt is some pv {- pin = pv- }- }- val repo_name: bytes.Bytes = client.url_repo_name(url)- val c_opt = client.connect_pinned(url, key, repo_name, pin)- bytes.free_owned(url)- if key.ptr != none {- bytes.free_owned(key)- }- if repo_name.ptr != none {- bytes.free_owned(repo_name)- }- val c: mut ref client.Client = none- match c_opt {- some v => {- c = v- }- none => {- val detail: bytes.Bytes = client.last_connect_error()- cmsg.error_prefix()- if detail.len > 0 {- stdio.eprint("{s}\n", {str.view(detail.ptr, detail.len as i64)})- } else {- stdio.eprint("cannot connect or authenticate\n", {})- }- bytes.free_owned(detail)- layout.free_repo(repo)- return 1- }- }- val refs_opt = client.list_refs(c)- if refs_opt is none {- report_client_error(c, bytes.bytes(c"cannot list remote refs", 23))- client.free_client(c)- layout.free_repo(repo)- return 1- }- val refs: mut list[msg_refs.RefInfo] = lists.new[msg_refs.RefInfo]()- match refs_opt {- some rv => {- refs = rv- }- none => {- return 1- }- }- val st: store.Store = store.open_all(repo)- val haves: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()- val hs: list[objid.Id] = state.heads(repo)- for h in hs {- @append(haves, bytes.Bytes.dup(bytes.bytes(h.ptr, 32)))- }- graph_free_ids(hs)- val wants: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()- for r in refs {- if r.target.ptr != none {- @append(wants, bytes.Bytes.dup(bytes.bytes(r.target.ptr, 32)))- }- }- if @len(wants) == 0 {- transfer.free_id_bytes(haves)- @listfree(wants)- store.close(st)- msg_refs.free_refs(refs)- client.free_client(c)- layout.free_repo(repo)- cmsg.info_prefix()- stdio.print("no refs to fetch\n", {})- return 0- }- if !client.negotiate(c, wants, haves) {- report_client_error(c, bytes.bytes(c"negotiation failed", 18))- transfer.free_id_bytes(wants)- transfer.free_id_bytes(haves)- store.close(st)- client.free_client(c)- layout.free_repo(repo)- return 1- }- val passed: bool = client.fetch_skeleton(c, repo, wants)- transfer.free_id_bytes(wants)- transfer.free_id_bytes(haves)- store.close(st)- if !passed {- report_client_error(c, bytes.bytes(c"fetch failed", 12))- client.free_client(c)- layout.free_repo(repo)- return 1- }- val st2: store.Store = store.open_all(repo)- val commits: mut list[objid.Id] = lists.new[objid.Id]()- for r in refs {- if r.target.ptr != none {- @append(commits, objid.id(r.target.ptr))- }- }- val chunks: list[bytes.Bytes] = transfer.chunks_for_commits(st2.handles, commits)- val chunks_ok: bool = send_chunks(c, repo, chunks)- transfer.free_id_bytes(chunks)- @listfree(commits)- store.close(st2)- if !chunks_ok {- report_client_error(c, bytes.bytes(c"chunk fetch failed", 18))- client.free_client(c)- layout.free_repo(repo)- return 1- }- val applied: i32 = transfer.apply_refs(repo, refs, remote_name, false)- msg_refs.free_refs(refs)- client.free_client(c)- layout.free_repo(repo)- if applied != 0 {- cmsg.error_prefix()- stdio.eprint("cannot write repository state\n", {})- return 1- }- cmsg.info_prefix()- stdio.print("fetched from {s}\n", {str.view(remote_name.ptr, remote_name.len as i64)})- bytes.free_owned(remote_name)- return 0-}--fn graph_free_ids(ids: list[objid.Id]) void = trust {- for x in ids {- if x.ptr != none {- bytes.free_owned(x)- }- }- @listfree(ids)-}--- a/veins/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/veins/src/cli/git_cmd.sx+++ /dev/null@@ -1,381 +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")-val materialize = use("../git/materialize.sx")-val remote = use("../git/remote.sx")-val config = use("../core/repoconfig.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, export, materialize, fetch, push, remote)\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)- }- if @strcmp(sub, c"materialize") == 0 {- return run_materialize(args, start + 1)- }- if @strcmp(sub, c"fetch") == 0 {- return run_fetch(args, start + 1)- }- if @strcmp(sub, c"push") == 0 {- return run_push(args, start + 1)- }- if @strcmp(sub, c"remote") == 0 {- return run_remote(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()- if prepared == 2 {- stdio.eprint(- "-source: {s} is not a git repository root (expected the directory containing .git)\n",- {src}- )- } else {- stdio.eprint("cannot prepare git mirror from {s} (code {d})\n", {src, 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-}--fn run_materialize(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 = materialize.run(repo)- layout.free_repo(repo)- return status-}--fn open_repo(path: str.StringView) option[layout.Repo] = trust {- return layout.discover(path)-}--fn run_fetch(args: list[ref u8], start: usize) i32 = trust {- val remote_name: mut bytes.Bytes = bytes.Bytes.dup(bytes.bytes(c"origin", 6))- val path: mut str.StringView = str.from_cstr(c".")- val have_remote: mut bool = false- 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)- if av.len > 0 && bytes.Bytes.at(av, 0) == 45 {- msg.error_prefix()- stdio.eprint("unknown flag: {s}\n", {str.from_cstr(a)})- bytes.free_ptr(remote_name.ptr)- return 1- } elif !have_remote {- remote_name = bytes.Bytes.dup(av)- have_remote = true- } else {- path = str.from_cstr(a)- }- }- i++- }- val repo_opt = open_repo(path)- val repo: mut layout.Repo = layout.Repo{root: bytes.empty()}- match repo_opt {- some r => {- repo = r- }- none => {- msg.error_prefix()- stdio.eprint("not a veins repository\n", {})- @free(remote_name.ptr as ref void)- return 1- }- }- val code: i32 = remote.fetch(repo, remote_name)- layout.free_repo(repo)- @free(remote_name.ptr as ref void)- return code-}--fn run_push(args: list[ref u8], start: usize) i32 = trust {- val remote_name: mut bytes.Bytes = bytes.Bytes.dup(bytes.bytes(c"origin", 6))- val bookmark: mut bytes.Bytes = bytes.empty()- val path: mut str.StringView = str.from_cstr(c".")- val have_remote: mut bool = false- 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)- 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- } elif !have_remote {- remote_name = bytes.Bytes.dup(av)- have_remote = true- } elif bookmark.ptr == none {- bookmark = bytes.Bytes.dup(av)- } else {- path = str.from_cstr(a)- }- }- i++- }- if bookmark.ptr == none {- msg.error_prefix()- stdio.eprint("git push requires a bookmark\n", {})- @free(remote_name.ptr as ref void)- return 1- }- val repo_opt = open_repo(path)- val repo: mut layout.Repo = layout.Repo{root: bytes.empty()}- match repo_opt {- some r => {- repo = r- }- none => {- msg.error_prefix()- stdio.eprint("not a veins repository\n", {})- return 1- }- }- val code: i32 = remote.push(repo, remote_name, bookmark)- layout.free_repo(repo)- @free(remote_name.ptr as ref void)- @free(bookmark.ptr as ref void)- return code-}--fn run_remote(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 remote subcommand (add, list, remove)\n", {})- return 1- }- }- val repo_opt = open_repo(str.from_cstr(c"."))- val repo: mut layout.Repo = layout.Repo{root: bytes.empty()}- match repo_opt {- some r => {- repo = r- }- none => {- msg.error_prefix()- stdio.eprint("not a veins repository\n", {})- return 1- }- }- if @strcmp(sub, c"add") == 0 {- val name_opt = @get(args, start + 1)- val url_opt = @get(args, start + 2)- val name: mut bytes.Bytes = bytes.empty()- val url: mut bytes.Bytes = bytes.empty()- if name_opt is some n {- name = bytes.from_cstr(n)- }- if url_opt is some u {- url = bytes.from_cstr(u)- }- if name.ptr == none || url.ptr == none {- msg.error_prefix()- stdio.eprint("remote add requires a name and URL\n", {})- layout.free_repo(repo)- return 1- }- val k: bytes.Bytes = remote.key_for(name, bytes.bytes(c"url", 3))- val passed: bool = config.set(repo, k, url)- bytes.free_ptr(k.ptr)- layout.free_repo(repo)- if !passed {- msg.error_prefix()- stdio.eprint("cannot write repository config\n", {})- return 1- }- return 0- }- if @strcmp(sub, c"list") == 0 || @strcmp(sub, c"ls") == 0 {- val names = remote.list_remotes(repo)- for n in names {- val u = remote.url_of(repo, n)- val url: mut bytes.Bytes = bytes.empty()- if u is some x {- url = x- }- stdio.print(- "{s}\t{s}\n",- {str.view(n.ptr, n.len as i64), str.view(url.ptr, url.len as i64)}- )- if url.ptr != none {- @free(url.ptr as ref void)- }- bytes.free_ptr(n.ptr)- }- @listfree(names)- layout.free_repo(repo)- return 0- }- if @strcmp(sub, c"remove") == 0 || @strcmp(sub, c"rm") == 0 {- val name_opt = @get(args, start + 1)- if name_opt is none {- msg.error_prefix()- stdio.eprint("remote remove requires a name\n", {})- layout.free_repo(repo)- return 1- }- val name: mut bytes.Bytes = bytes.empty()- if name_opt is some nv {- name = bytes.from_cstr(nv)- }- val k: bytes.Bytes = remote.key_for(name, bytes.bytes(c"url", 3))- val k2: bytes.Bytes = remote.key_for(name, bytes.bytes(c"key", 3))- val k3: bytes.Bytes = remote.key_for(name, bytes.bytes(c"tls-pin", 7))- config.remove(repo, k)- config.remove(repo, k2)- config.remove(repo, k3)- bytes.free_ptr(k.ptr)- bytes.free_ptr(k2.ptr)- bytes.free_ptr(k3.ptr)- layout.free_repo(repo)- return 0- }- layout.free_repo(repo)- msg.error_prefix()- stdio.eprint("unknown remote subcommand: {s}\n", {str.from_cstr(sub)})- return 1-}--- a/veins/src/cli/hash_cmd.sx+++ /dev/null@@ -1,143 +0,0 @@-/// `vn hash [rev]`: print the full commit hash for a revision.--val str = use("std/string")-val stdio = use("std/stdio")-val msg = use("../core/msg.sx")-val bytes = use("../core/bytes.sx")-val objid = use("../object/id.sx")-val graph = use("../object/graph.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 snapshot = use("../worktree/snapshot.sx")--fn cmd_is(a: ref u8, text: ref u8, len: usize) bool = trust {- 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 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_id(id: objid.Id) void = trust {- if id.ptr != none {- val p: mut ref void = id.ptr as ref void- @free(p)- }-}--pub fn run(args: list[ref u8], start: usize) i32 = trust {- val rev: mut bytes.Bytes = bytes.empty()- val short: 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"-short", 6) {- short = true- } elif !end_flags && cmd_is(a, c"-long", 5) {- short = false- } 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 && 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 = layout.discover(str.from_cstr(c"."))- 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\n", {})- return 1- }- }-- val snap: i32 = snapshot.run(repo)- if snap != 0 {- layout.free_repo(repo)- 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 => {- msg.error_prefix()- stdio.eprint("no operation state\n", {})- store.close(st)- layout.free_repo(repo)- return 1- }- }- val resolved = graph.resolve(st.handles, v, rev)- val target: mut objid.Id = objid.id_none()- val have_target: mut bool = false- if resolved is some id {- target = copy_id(id)- have_target = true- }- view.free_view(v)- if !have_target {- msg.error_prefix()- if rev.len == 0 {- stdio.eprint("no working-copy commit\n", {})- } else {- stdio.eprint("unknown revision: {s}\n", {str.view(rev.ptr, rev.len as i64)})- }- store.close(st)- layout.free_repo(repo)- return 1- }-- val hex: ref u8 = objid.Id.hex(target)- val width: mut usize = 64- if short {- width = 12- }- stdio.print("{s}\n", {str.view(hex, width)})- @free(hex as ref void)- free_id(target)- store.close(st)- layout.free_repo(repo)- return 0-}--- a/veins/src/cli/help_cmd.sx+++ /dev/null@@ -1,692 +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("subcommands:")- stdio.puts(" init create a repository")- stdio.puts(" git import from or export to git")- stdio.puts(" remote manage native remotes")- stdio.puts(" clone clone a repository over the native protocol")- stdio.puts(" fetch fetch from a native remote")- stdio.puts(" push push a bookmark to a native remote")- stdio.puts(" serve run the native server over stdio or TLS")- stdio.puts(" key manage local Ed25519 keys")- stdio.puts(" auth remember keys for hosts and set a default")- stdio.puts(" access manage a served repository's access file")- stdio.puts(" whoami report the role granted by a server")- stdio.puts(" co write a revision into the working directory; alias: checkout")- stdio.puts(" stat show working-copy changes; alias: status")- stdio.puts(" ls list tracked files")- stdio.puts(" inf show a repository breakdown")- stdio.puts(" log show commit history")- stdio.puts(" show show a commit and its diff")- stdio.puts(" hash print the commit hash for a revision")- stdio.puts(" diff show a unified diff")- stdio.puts(" merge create a merge commit; never fails")- stdio.puts(" rebase rewrite changes onto a new parent")- stdio.puts(" xs list conflicted paths")- stdio.puts(" resolve resolve a conflicted path")- stdio.puts(" new start a new change")- stdio.puts(" bmk manage named branch pointers")- stdio.puts(" tag manage named tags")- stdio.puts(" cfg read and write configuration")- stdio.puts(" rm untrack paths, keeping files on disk by default")- stdio.puts(" mv move a tracked file and record the rename")- stdio.puts(" ex add paths or globs to .vnexclude")- stdio.puts(" desc set the working-copy commit message; alias: describe")- stdio.puts(" go describe and start a new change; alias: commit")- stdio.puts(" amend rewrite a revision's message and its descendants")- 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 from <gitdir> (a directory containing .git)")-}--fn show_remote() void = trust {- stdio.puts("usage: vn remote <add|set-url|list|remove> ...")- stdio.puts("")- stdio.puts("manage native remotes stored in .veins/config")- stdio.puts("")- stdio.puts("subcommands:")- stdio.puts(" add <name> <url> [-key:<name>] [-pin:<hash>]")- stdio.puts(" add a remote")- stdio.puts(" set-url <name> <url> [-key:<name>] [-pin:<hash>]")- stdio.puts(" change a remote URL (and optionally key/pin)")- stdio.puts(" list list remotes")- stdio.puts(" remove <name> remove a remote")- stdio.puts("")- stdio.puts("an empty -key: or -pin: value clears that setting")- stdio.puts("")- stdio.puts("examples:")- stdio.puts(" vn remote add origin veins://127.0.0.1:7419/navid-m/veins2")- stdio.puts(" vn remote set-url origin veins://example/repo -key:my-key")-}--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(" materialize [path] replace lazy git blobs with stored blobs")- stdio.puts(" fetch [<remote>] [path] git fetch into the mirror, then import")- stdio.puts(" push [<remote>] <bookmark> [path]")- stdio.puts(" export and git push a bookmark")- stdio.puts(" remote <add|list|remove> manage git remotes")- 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("an empty working tree is checked out to the imported head")- stdio.puts("")- stdio.puts("arguments:")- stdio.puts(" [path] veins repository (default: .)")- stdio.puts("")- stdio.puts("options:")- stdio.puts(" -source:<gitdir> source git root to mirror (a directory containing .git)")-}--fn show_checkout() void = trust {- stdio.puts("usage: vn co [rev]")- stdio.puts("")- stdio.puts("write a revision into the working directory")- stdio.puts("")- stdio.puts("aliases: checkout")- 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_merge() void = trust {- stdio.puts("usage: vn merge <rev>...")- stdio.puts("")- stdio.puts("create a merge commit from the working-copy commit and the revisions")- stdio.puts("the merge never fails; conflicts are stored as conflict values")-}--fn show_rebase() void = trust {- stdio.puts("usage: vn rebase -s <rev> -d <rev>")- stdio.puts("")- stdio.puts("rewrite the source change and its descendants onto the destination")- stdio.puts("")- stdio.puts("options:")- stdio.puts(" -s, -source <rev> first change to rewrite")- stdio.puts(" -d, -destination <rev> new parent")-}--fn show_xs() void = trust {- stdio.puts("usage: vn xs [-porcelain]")- stdio.puts("")- stdio.puts("list conflicted paths and, for text conflicts, conflicting line ranges")- stdio.puts("")- stdio.puts("porcelain columns (tab-separated):")- stdio.puts(" path, kind, base-ranges, ours-ranges, theirs-ranges")-}--fn show_resolve() void = trust {- stdio.puts("usage: vn resolve [-take ours|theirs|base] [-tool <cmd>] <path>...")- stdio.puts(" vn resolve -list")- stdio.puts("")- stdio.puts("resolve conflicted paths. Without -take, the current file content is")- stdio.puts("recorded as the resolution. -tool substitutes $BASE, $OURS, $THEIRS,")- stdio.puts("and $OUTPUT in the command.")-}--fn show_status() void = trust {- stdio.puts("usage: vn stat")- stdio.puts("")- stdio.puts("show working-copy changes relative to the parent commit")- stdio.puts("")- stdio.puts("aliases: status")-}--fn show_ls() void = trust {- stdio.puts("usage: vn ls [rev] [-plain]")- stdio.puts("")- stdio.puts("list tracked files as an ASCII tree")- stdio.puts("")- stdio.puts("arguments:")- stdio.puts(" [rev] revision to list (default: @)")- stdio.puts("")- stdio.puts("options:")- stdio.puts(" -rev <rev> revision to list")- stdio.puts(" -plain, -p print one tracked path per line")-}--fn show_inf() void = trust {- stdio.puts("usage: vn inf")- stdio.puts("")- stdio.puts("show a repository overview with a language breakdown by file extension,")- stdio.puts("line-of-code shares, author commit shares, and repository metadata")-}--fn show_log() void = trust {- stdio.puts("usage: vn log [-rev <revset>] [-lN | -fN] [-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(" -lN, -l <N> show the last N commits (newest N)")- stdio.puts(" -fN, -f <N> show the first N commits (oldest N)")- stdio.puts(" -no-col-titles omit column titles")-}--fn show_show() void = trust {- stdio.puts("usage: vn show [rev] [-no-col-titles]")- stdio.puts("")- stdio.puts("show a commit's metadata and its diff against its first parent")- stdio.puts("")- stdio.puts("arguments:")- stdio.puts(" [rev] revision to show (default: @)")- stdio.puts("")- stdio.puts("options:")- stdio.puts(" -no-col-titles omit the metadata labels")-}--fn show_hash() void = trust {- stdio.puts("usage: vn hash [rev] [-short|-long]")- stdio.puts("")- stdio.puts("print the commit hash for a revision")- stdio.puts("")- stdio.puts("arguments:")- stdio.puts(" [rev] revision to hash (default: @)")- stdio.puts("")- stdio.puts("options:")- stdio.puts(" -rev <rev> revision to hash")- stdio.puts(" -short print the 12-character abbreviated hash")- stdio.puts(" -long print the full 64-character hash (default)")-}--fn show_bookmark() void = trust {- stdio.puts("usage: vn bmk <set|mv|ls|rm> ...")- stdio.puts("")- stdio.puts("manage named, movable pointers to commits (branches)")- stdio.puts("")- stdio.puts("subcommands:")- stdio.puts(" set <name> [-rev <rev>] create or move a bookmark (default: @)")- stdio.puts(" mv <name> [-rev <rev>] alias of set")- stdio.puts(" ls [-no-col-titles] list bookmarks")- stdio.puts(" rm <name> delete a bookmark")- stdio.puts("")- stdio.puts("examples:")- stdio.puts(" vn bmk set main")- stdio.puts(" vn new main")- stdio.puts(" vn co main")-}--fn show_tag() void = trust {- stdio.puts("usage: vn tag <set|ls|rm|latest> ...")- stdio.puts("")- stdio.puts("manage named pointers to commits (tags)")- stdio.puts("")- stdio.puts("subcommands:")- stdio.puts(" set <name> [-rev <rev>] create or move a tag (default: @)")- stdio.puts(" ls [-no-col-titles] list tags")- stdio.puts(" rm <name> delete a tag")- stdio.puts(" latest print the latest tag name")- stdio.puts("")- stdio.puts("the latest tag is the one whose target commit has the newest")- stdio.puts("committer timestamp; equal timestamps use natural name order")-}--fn show_cfg() void = trust {- stdio.puts("usage: vn cfg [<key>] [<value>]")- stdio.puts(" vn cfg [<get|set|unset|list>] [<key>] [<value>]")- stdio.puts(" vn cfg -list")- stdio.puts(" vn cfg -unset <key>")- stdio.puts("")- stdio.puts("read and write local repository configuration")- stdio.puts("")- stdio.puts(" vn cfg list all keys")- stdio.puts(" vn cfg <key> print a value")- stdio.puts(" vn cfg <key> <value> set a value")- stdio.puts(" vn cfg -unset <key> remove a key")- stdio.puts(" vn cfg -global ... use the user config instead")-}--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_mv() void = trust {- stdio.puts("usage: vn mv <from> <to>")- stdio.puts("")- stdio.puts("move a tracked file; the following snapshot records the rename")-}--fn show_rm() void = trust {- stdio.puts("usage: vn rm [-delete] <path>...")- stdio.puts("")- stdio.puts("remove paths from the working-copy tree")- stdio.puts("")- stdio.puts("files stay on disk by default. Arguments may be paths or globs and are")- stdio.puts("resolved relative to the current directory. Supported wildcards are")- stdio.puts("'*', '?', and '**'; '*' and '?' do not cross directory separators.")- stdio.puts("")- stdio.puts("options:")- stdio.puts(" -delete delete matching files from disk after untracking")-}--fn show_ex() void = trust {- stdio.puts("usage: vn ex <pattern>...")- stdio.puts("")- stdio.puts("append ignore patterns to the repository root .vnexclude")- stdio.puts("")- stdio.puts("patterns use gitignore syntax and are resolved relative to the current")- stdio.puts("directory. Quote wildcard patterns so the shell does not expand them:")- stdio.puts(" vn ex '*.dSYM'")-}--fn show_describe() void = trust {- stdio.puts("usage: vn desc [-message <message>] [<message>]")- stdio.puts("")- stdio.puts("set the working-copy commit message")- stdio.puts("")- stdio.puts("aliases: describe")-}--fn show_commit() void = trust {- stdio.puts("usage: vn go -message <message>")- stdio.puts("")- stdio.puts("set the message and start a new change")- stdio.puts("")- stdio.puts("a non-empty commit message is required")- stdio.puts("")- stdio.puts("aliases: commit")-}--fn show_amend() void = trust {- stdio.puts("usage: vn amend <rev> -m <message>")- stdio.puts("")- stdio.puts("rewrite a revision's message and update its descendants")- stdio.puts("")- stdio.puts("options:")- stdio.puts(" -m, -message <message> new commit message")- stdio.puts("")- stdio.puts("revisions reachable from a remote ref cannot be amended")-}--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_git_materialize() void = trust {- stdio.puts("usage: vn git materialize [path]")- stdio.puts("")- stdio.puts("replace lazy git-backed blobs with canonical stored blobs")- stdio.puts("")- stdio.puts("rewrites affected trees, commits, and refs and records one operation")-}--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")-}---fn show_clone() void = trust {- stdio.puts("usage: vn clone <url> [-blobs:<head|none|all>] [-key:<name>] [-pin:<sha256>] [path]")- stdio.puts("")- stdio.puts("clone a repository over file://, ssh://, or veins://")- stdio.puts("")- stdio.puts("without -key, the key stored by 'vn auth use' is used when available")-}--fn show_fetch() void = trust {- stdio.puts("usage: vn fetch [-key:<name>] [<remote>] [path]")- stdio.puts("")- stdio.puts("fetch new history and chunks from a configured native remote")- stdio.puts("")- stdio.puts("auth falls back to remote.<name>.key, then 'vn auth use'")-}--fn show_push() void = trust {- stdio.puts("usage: vn push [-key:<name>] [<remote>] [<bookmark>] [path]")- stdio.puts("")- stdio.puts("push a bookmark to a configured native remote")- stdio.puts("")- stdio.puts("without <bookmark>, the current bookmark is pushed")- stdio.puts("auth falls back to remote.<name>.key, then 'vn auth use'")-}--fn show_serve() void = trust {- stdio.puts("usage: vn serve -stdio <repo> [-quota <bytes>]")- stdio.puts(" vn serve -listen <addr:port> -root <dir> -tls-cert <file> -tls-key <file> [-quota <bytes>]")- stdio.puts("")- stdio.puts("run the native server over standard input/output or TLS 1.3")- stdio.puts("-quota limits stored pack and index bytes per top-level namespace")-}--fn show_key() void = trust {- stdio.puts("usage: vn key <generate|list|show> [name]")- stdio.puts("")- stdio.puts("manage local Ed25519 keys in the user key directory")-}--fn show_auth() void = trust {- stdio.puts("usage: vn auth <use|list|remove> ...")- stdio.puts("")- stdio.puts("remember which key clone/fetch/push should use")- stdio.puts("")- stdio.puts(" vn auth use <key> [<host|url>] set the default or host key")- stdio.puts(" vn auth list show stored key mappings")- stdio.puts(" vn auth remove [<host|url>] remove a mapping")-}--fn show_access() void = trust {- stdio.puts("usage: vn access <add|list|remove|anonymous> ...")- stdio.puts("")- stdio.puts("manage a served repository's .veins/access policy")-}--fn show_whoami() void = trust {- stdio.puts("usage: vn whoami [<remote>|<url>]")- stdio.puts("")- stdio.puts("connect to a server and report the granted role and key fingerprint")-}--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"stat", 4) || cmd_is(cmd, c"status", 6) {- show_status()- return 0- }- if cmd_is(cmd, c"ls", 2) {- show_ls()- return 0- }- if cmd_is(cmd, c"inf", 3) {- show_inf()- return 0- }- if cmd_is(cmd, c"log", 3) {- show_log()- return 0- }- if cmd_is(cmd, c"show", 4) {- show_show()- return 0- }- if cmd_is(cmd, c"hash", 4) {- show_hash()- return 0- }- if cmd_is(cmd, c"diff", 4) {- show_diff()- return 0- }- if cmd_is(cmd, c"merge", 5) {- show_merge()- return 0- }- if cmd_is(cmd, c"rebase", 6) {- show_rebase()- return 0- }- if cmd_is(cmd, c"xs", 2) {- show_xs()- return 0- }- if cmd_is(cmd, c"resolve", 7) {- show_resolve()- return 0- }- if cmd_is(cmd, c"bmk", 3) {- show_bookmark()- return 0- }- if cmd_is(cmd, c"tag", 3) {- show_tag()- return 0- }- if cmd_is(cmd, c"cfg", 3) || cmd_is(cmd, c"config", 6) {- show_cfg()- return 0- }- if cmd_is(cmd, c"new", 3) {- show_new()- return 0- }- if cmd_is(cmd, c"rm", 2) {- show_rm()- return 0- }- if cmd_is(cmd, c"mv", 2) {- show_mv()- return 0- }- if cmd_is(cmd, c"ex", 2) {- show_ex()- return 0- }- if cmd_is(cmd, c"desc", 4) || cmd_is(cmd, c"describe", 8) {- show_describe()- return 0- }- if cmd_is(cmd, c"go", 2) || cmd_is(cmd, c"commit", 6) {- show_commit()- return 0- }- if cmd_is(cmd, c"amend", 5) {- show_amend()- 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"clone", 5) {- show_clone()- return 0- }- if cmd_is(cmd, c"fetch", 5) {- show_fetch()- return 0- }- if cmd_is(cmd, c"push", 4) {- show_push()- return 0- }- if cmd_is(cmd, c"serve", 5) {- show_serve()- return 0- }- if cmd_is(cmd, c"key", 3) {- show_key()- return 0- }- if cmd_is(cmd, c"auth", 4) {- show_auth()- return 0- }- if cmd_is(cmd, c"access", 6) {- show_access()- return 0- }- if cmd_is(cmd, c"whoami", 6) {- show_whoami()- return 0- }- if cmd_is(cmd, c"remote", 6) {- show_remote()- 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- }- if cmd_is(sub, c"materialize", 11) {- show_git_materialize()- return 0- }- if cmd_is(sub, c"fetch", 5) {- stdio.puts("usage: vn git fetch [<remote>] [path]")- return 0- }- if cmd_is(sub, c"push", 4) {- stdio.puts("usage: vn git push [<remote>] <bookmark> [path]")- return 0- }- if cmd_is(sub, c"remote", 6) {- stdio.puts("usage: vn git remote <add|list|remove> ...")- 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"co", 2) || 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/veins/src/cli/inf_cmd.sx+++ /dev/null@@ -1,709 +0,0 @@-/// `vn inf`: show a onefetch-style breakdown of the repository.-///-/// File statistics come from the recorded working-copy commit (no implicit-/// snapshot is created). Author statistics cover every commit reachable from-/// the current operation view. All work is done with the portable Spectre-/// standard library; no external tools are invoked.--val str = use("std/string")-val stdio = use("std/stdio")-val terminal = use("std/terminal")-val fs = use("std/fs")-val bytes = use("../core/bytes.sx")-val lists = use("../core/lists.sx")-val datetime = use("../core/datetime.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 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 BAR_WIDTH: u64 = 24--type GitSource = {- repo: mut object.GitRepo- open: mut bool-}--type ExtStat = {- ext: mut bytes.Bytes- files: mut u64- lines: mut u64- bytes: mut u64-}--type AuthorStat = {- name: mut bytes.Bytes- commits: mut u64-}--type Totals = {- files: mut u64- lines: mut u64- bytes: mut u64-}--type History = {- commits: mut u64- created: mut i64- last: mut i64- has_time: mut bool-}--fn open_git(repo: layout.Repo) GitSource = trust {- val p: str.StringView = layout.git_dir(repo)- val r = object.open(p)- val g: mut GitSource = GitSource{repo: @zeroed, open: false}- match r {- ok x => {- // object.open takes ownership of the path on success.- g.repo = x- g.open = true- }- err _ => {- files.free_path(p)- }- }- return g-}--fn close_git(g: mut GitSource) void = trust {- if g.open {- object.free(g.repo)- g.open = false- }-}--fn new_ext(ext: bytes.Bytes) ref ExtStat = trust {- val e: mut ref ExtStat = @alloc(@sizeof(ExtStat)) as ref ExtStat- e.ext = ext- e.files = 0- e.lines = 0- e.bytes = 0- return e-}--fn free_exts(xs: list[ref ExtStat]) void = trust {- for e in xs {- if e.ext.ptr != none {- val p: mut ref void = e.ext.ptr as ref void- @free(p)- }- val ep: mut ref void = e as ref void- @free(ep)- }- @listfree(xs)-}--fn new_author(name: bytes.Bytes) ref AuthorStat = trust {- val a: mut ref AuthorStat = @alloc(@sizeof(AuthorStat)) as ref AuthorStat- a.name = bytes.Bytes.dup(name)- a.commits = 0- return a-}--fn free_authors(xs: list[ref AuthorStat]) void = trust {- for a in xs {- if a.name.ptr != none {- val p: mut ref void = a.name.ptr as ref void- @free(p)- }- val ap: mut ref void = a as ref void- @free(ap)- }- @listfree(xs)-}--fn find_ext(xs: list[ref ExtStat], ext: bytes.Bytes) option[ref ExtStat] = trust {- for e in xs {- if bytes.Bytes.eql(e.ext, ext) {- return some e- }- }- return none-}--fn find_author(xs: list[ref AuthorStat], name: bytes.Bytes) option[ref AuthorStat] = trust {- for a in xs {- if bytes.Bytes.eql(a.name, name) {- return some a- }- }- return none-}--fn ascii_lower(c: u8) u8 = trust {- if c >= 65 && c <= 90 {- return (c + 32) as u8- }- return c-}--/// Return the lowercased extension of a path, including the leading dot.-fn ext_of(path: bytes.Bytes) bytes.Bytes = trust {- val base_start: mut usize = 0- val i: mut usize = 0- for i < path.len {- if bytes.Bytes.at(path, i) == 47 {- base_start = i + 1- }- i++- }- val dot: mut i64 = -1- val j: mut usize = base_start- for j < path.len {- if bytes.Bytes.at(path, j) == 46 {- dot = j as i64- }- j++- }- if dot < 0 || (dot as usize) <= base_start || (dot as usize) + 1 >= path.len {- return bytes.Bytes.dup(bytes.bytes(c"(none)", 6))- }- val raw: bytes.Bytes = bytes.Bytes.slice(path, dot as usize, path.len)- val out: ref u8 = @alloc(raw.len) as ref u8- val k: mut usize = 0- for k < raw.len {- @store8(@ptradd(out, k as i64), ascii_lower(bytes.Bytes.at(raw, k)))- k++- }- return bytes.bytes(out, raw.len)-}--fn is_blank_char(c: u8) bool = trust {- return c == 32 || c == 9 || c == 13-}--fn looks_binary(data: bytes.Bytes) bool = trust {- val limit: usize = 8192- val n: mut usize = limit- if data.len < limit {- n = data.len- }- val i: mut usize = 0- for i < n {- if bytes.Bytes.at(data, i) == 0 {- return true- }- i++- }- return false-}--/// Count newline-separated lines that contain a non-whitespace byte.-fn count_nonblank(data: bytes.Bytes) u64 = trust {- val count: mut u64 = 0- val i: mut usize = 0- for i < data.len {- val line_end: mut usize = i- for line_end < data.len && bytes.Bytes.at(data, line_end) != 10 {- line_end++- }- val blank: mut bool = true- val j: mut usize = i- for j < line_end {- if !is_blank_char(bytes.Bytes.at(data, j)) {- blank = false- break- }- j++- }- if !blank {- count++- }- if line_end >= data.len {- i = data.len- } else {- i = line_end + 1- }- }- return count-}--fn add_file(stats: mut list[ref ExtStat], path: bytes.Bytes, lines: u64, size: u64) void = trust {- val ext: bytes.Bytes = ext_of(path)- val found = find_ext(stats, ext)- if found is some e {- e.files++- e.lines += lines- e.bytes += size- if ext.ptr != none {- val p: mut ref void = ext.ptr as ref void- @free(p)- }- return- }- val e2: mut ref ExtStat = new_ext(ext)- e2.files = 1- e2.lines = lines- e2.bytes = size- @append(stats, e2)-}--fn analyze_files(- handles: list[ref store.Handle],- root_tree: objid.Id,- git: object.GitRepo,- has_git: bool,- stats: mut list[ref ExtStat]-) Totals = trust {- val totals: mut Totals = Totals{files: 0, lines: 0, bytes: 0}- val entries: list[ref treewalk.FlatEntry] = treewalk.flatten(handles, root_tree)- for e in entries {- if e.kind == tree.KIND_FILE || e.kind == tree.KIND_EXECUTABLE {- totals.files++- val data_opt = content.read_blob(handles, e.target, git, has_git)- val lines: mut u64 = 0- val size: mut u64 = 0- if data_opt is some data {- size = data.len as u64- totals.bytes += size- if !looks_binary(data) {- lines = count_nonblank(data)- }- totals.lines += lines- add_file(stats, e.path, lines, size)- files.free_buffer(data)- } else {- add_file(stats, e.path, 0, 0)- }- }- }- treewalk.free_flat(entries)- return totals-}--fn collect_history(- handles: list[ref store.Handle],- v: ref view.View,- authors: mut list[ref AuthorStat]-) History = trust {- val hist: mut History = History{commits: 0, created: 0, last: 0, has_time: false}- val roots: list[objid.Id] = graph.roots(v)- val ids: list[objid.Id] = graph.collect(handles, roots)- graph.free_ids(roots)- for id in ids {- val lc_opt = graph.load_commit(handles, id)- if lc_opt is some lc {- hist.commits++- val secs: i64 = lc.c.committer.seconds- if !hist.has_time {- hist.created = secs- hist.last = secs- hist.has_time = true- } else {- if secs < hist.created {- hist.created = secs- }- if secs > hist.last {- hist.last = secs- }- }- val found = find_author(authors, lc.c.author.name)- if found is some a {- a.commits++- } else {- val name: mut bytes.Bytes = lc.c.author.name- if name.len == 0 {- name = bytes.bytes(c"(unknown)", 9)- }- val a2: mut ref AuthorStat = new_author(name)- a2.commits = 1- @append(authors, a2)- }- graph.free_loaded(lc)- }- }- graph.free_ids(ids)- return hist-}--fn sort_exts(xs: mut list[ref ExtStat]) void = trust {- val i: mut usize = 1- for i < @len(xs) {- val cur_opt = @get(xs, i)- val cur: mut ref ExtStat = none- if cur_opt is some c {- cur = c- }- val j: mut usize = i- for j > 0 {- val prev_opt = @get(xs, j - 1)- val prev: mut ref ExtStat = none- if prev_opt is some p {- prev = p- }- val keep: bool = prev.lines > cur.lines- || (prev.lines == cur.lines && bytes.Bytes.cmp(prev.ext, cur.ext) <= 0)- if keep {- break- }- @set(xs, j, prev)- j--- }- @set(xs, j, cur)- i++- }-}--fn sort_authors(xs: mut list[ref AuthorStat]) void = trust {- val i: mut usize = 1- for i < @len(xs) {- val cur_opt = @get(xs, i)- val cur: mut ref AuthorStat = none- if cur_opt is some c {- cur = c- }- val j: mut usize = i- for j > 0 {- val prev_opt = @get(xs, j - 1)- val prev: mut ref AuthorStat = none- if prev_opt is some p {- prev = p- }- val keep: bool = prev.commits > cur.commits- || (prev.commits == cur.commits && bytes.Bytes.cmp(prev.name, cur.name) <= 0)- if keep {- break- }- @set(xs, j, prev)- j--- }- @set(xs, j, cur)- i++- }-}--fn print_left(- 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 color_for(i: usize) terminal.Color = trust {- val n: usize = i % 8- if n == 0 {- return terminal.Color.BrightCyan- }- if n == 1 {- return terminal.Color.BrightGreen- }- if n == 2 {- return terminal.Color.BrightYellow- }- if n == 3 {- return terminal.Color.BrightMagenta- }- if n == 4 {- return terminal.Color.BrightBlue- }- if n == 5 {- return terminal.Color.BrightRed- }- if n == 6 {- return terminal.Color.Cyan- }- return terminal.Color.Green-}--fn percent(num: u64, total: u64) u64 = trust {- if total == 0 {- return 0- }- return (num * 100 + total / 2) / total-}--fn print_percent(pct: u64) void = trust {- if pct < 10 {- stdio.print(" {d}", {pct})- } elif pct < 100 {- stdio.print(" {d}", {pct})- } else {- stdio.print("{d}", {pct})- }-}--fn print_bar(num: u64, total: u64, color: terminal.Color) void = trust {- val filled: mut u64 = 0- if total > 0 && num > 0 {- filled = (num * BAR_WIDTH + total / 2) / total- if filled == 0 {- filled = 1- }- if filled > BAR_WIDTH {- filled = BAR_WIDTH- }- }- terminal.print_repeat(str.from_cstr(c"█"), filled as i64, color)- terminal.print_repeat(- str.from_cstr(c"░"),- (BAR_WIDTH - filled) as i64,- terminal.Color.BrightBlack- )-}--fn row_value(label: str.StringView, value: str.StringView) void = trust {- print_left(label, 14, terminal.Color.Default, true)- stdio.print("{s}\n", {value})-}--fn row_number(label: str.StringView, value: u64) void = trust {- print_left(label, 14, terminal.Color.Default, true)- stdio.print("{d}\n", {value})-}--fn dir_size(path: str.StringView, depth: usize) u64 = trust {- if depth > 64 {- return 0- }- val names: list[ref u8] = files.list_dir(path)- val total: mut u64 = 0- for n in names {- val child: str.StringView = files.join(path, str.from_cstr(n))- if fs.is_directory(child) {- total += dir_size(child, depth + 1)- } else {- val sz = fs.file_size(child)- if sz is some size {- if size > 0 {- total += size as u64- }- }- }- files.free_path(child)- }- files.free_names(names)- return total-}--fn print_size(n: u64) void = trust {- if n >= 1073741824 {- val whole: u64 = n / 1073741824- val frac: u64 = ((n % 1073741824) * 10) / 1073741824- stdio.print("{d}.{d} GiB\n", {whole, frac})- } elif n >= 1048576 {- val whole: u64 = n / 1048576- val frac: u64 = ((n % 1048576) * 10) / 1048576- stdio.print("{d}.{d} MiB\n", {whole, frac})- } elif n >= 1024 {- val whole: u64 = n / 1024- val frac: u64 = ((n % 1024) * 10) / 1024- stdio.print("{d}.{d} KiB\n", {whole, frac})- } else {- stdio.print("{d} B\n", {n})- }-}--fn show_date(label: str.StringView, seconds: i64) void = trust {- val stamp: bytes.Bytes = datetime.format_utc(seconds)- val view_len: mut usize = stamp.len- if view_len > 10 {- view_len = 10- }- print_left(label, 14, terminal.Color.Default, true)- stdio.print("{s}\n", {str.view(stamp.ptr, view_len as i64)})- files.free_buffer(stamp)-}--fn print_languages(exts: mut list[ref ExtStat], totals: Totals) void = trust {- terminal.puts_styled(- "Languages",- terminal.Color.BrightCyan,- terminal.Color.Default,- terminal.Style.Bold- )- stdio.print("\n", {})- if @len(exts) == 0 {- stdio.print(" no tracked files\n", {})- return- }- sort_exts(exts)- val w_ext: mut usize = 6- val i: mut usize = 0- for i < @len(exts) {- val o = @get(exts, i)- if o is some e {- if e.ext.len > w_ext {- w_ext = e.ext.len- }- }- i++- }- val k: mut usize = 0- for k < @len(exts) {- val o = @get(exts, k)- if o is some e {- val ext_view: str.StringView = str.view(e.ext.ptr, e.ext.len as i64)- print_left(ext_view, w_ext, terminal.Color.Default, false)- stdio.print(" ", {})- print_bar(e.lines, totals.lines, color_for(k))- stdio.print(" ", {})- print_percent(percent(e.lines, totals.lines))- stdio.print(- "{s} {d} lines {d} files\n",- {str.from_cstr(c"%"), e.lines, e.files}- )- }- k++- }-}--fn print_authors(authors: mut list[ref AuthorStat], commits: u64) void = trust {- terminal.puts_styled(- "Authors",- terminal.Color.BrightCyan,- terminal.Color.Default,- terminal.Style.Bold- )- stdio.print("\n", {})- if @len(authors) == 0 {- stdio.print(" no commits\n", {})- return- }- sort_authors(authors)- val w_name: mut usize = 6- val i: mut usize = 0- for i < @len(authors) {- val o = @get(authors, i)- if o is some a {- if a.name.len > w_name {- w_name = a.name.len- }- }- i++- }- val k: mut usize = 0- for k < @len(authors) {- val o = @get(authors, k)- if o is some a {- val name_view: str.StringView = str.view(a.name.ptr, a.name.len as i64)- print_left(name_view, w_name, terminal.Color.Cyan, false)- stdio.print(" ", {})- print_bar(a.commits, commits, color_for(k))- stdio.print(" ", {})- print_percent(percent(a.commits, commits))- stdio.print("{s} {d} commits\n", {str.from_cstr(c"%"), a.commits})- }- k++- }-}--pub fn run(repo: layout.Repo) i32 = trust {- 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 => {- v = state.empty_view()- }- }-- val wc_opt = viewops.working_copy(v)- 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 wc_tree: mut option[objid.Id] = none- if have_wc {- val lc_opt = graph.load_commit(st.handles, wc)- if lc_opt is some lc {- wc_tree = some(graph.copy_id(lc.c.root_tree))- graph.free_loaded(lc)- }- }-- val git: mut GitSource = open_git(repo)- val exts: mut list[ref ExtStat] = lists.new[ref ExtStat]()- val authors: mut list[ref AuthorStat] = lists.new[ref AuthorStat]()-- val totals: mut Totals = Totals{files: 0, lines: 0, bytes: 0}- if wc_tree is some tree_id {- totals = analyze_files(st.handles, tree_id, git.repo, git.open, exts)- }- val hist: History = collect_history(st.handles, v, authors)-- stdio.print("\n", {})- terminal.puts_styled(- "Repository overview",- terminal.Color.BrightCyan,- terminal.Color.Default,- terminal.Style.Bold- )- stdio.print("\n", {})-- row_value(str.from_cstr(c"Project"), files.basename(layout.root_view(repo)))-- print_left(str.from_cstr(c"HEAD"), 14, terminal.Color.Default, true)- if have_wc {- val hex: ref u8 = objid.Id.hex(wc)- stdio.print("{s}\n", {str.view(hex, 12)})- @free(hex as ref void)- } else {- stdio.print("<none>\n", {})- }-- row_number(str.from_cstr(c"Changes"), hist.commits)- row_number(str.from_cstr(c"Bookmarks"), @len(v.bookmarks) as u64)- row_number(str.from_cstr(c"Tags"), @len(v.tags) as u64)- row_number(str.from_cstr(c"Files"), totals.files)- row_number(str.from_cstr(c"Lines"), totals.lines)- row_number(str.from_cstr(c"Authors"), @len(authors) as u64)- if hist.has_time {- show_date(str.from_cstr(c"Created"), hist.created)- show_date(str.from_cstr(c"Last change"), hist.last)- }- print_left(str.from_cstr(c"Size"), 14, terminal.Color.Default, true)- val veins_path: str.StringView = layout.veins_dir(repo)- print_size(dir_size(veins_path, 0))- files.free_path(veins_path)-- stdio.print("\n", {})- print_languages(exts, totals)- stdio.print("\n", {})- print_authors(authors, hist.commits)- stdio.print("\n", {})-- free_exts(exts)- free_authors(authors)- if wc_tree is some tree_id {- if tree_id.ptr != none {- val tp: mut ref void = tree_id.ptr as ref void- @free(tp)- }- }- if wc.ptr != none {- val wp: mut ref void = wc.ptr as ref void- @free(wp)- }- close_git(git)- view.free_view(v)- store.close(st)- return 0-}--- a/veins/src/cli/init_cmd.sx+++ /dev/null@@ -1,48 +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()- if prepared == 2 {- stdio.eprint(- "-git-import: {s} is not a git repository root (expected the directory containing .git)\n",- {src}- )- } else {- stdio.eprint(- "cannot prepare git mirror from {s} (code {d})\n",- {src, 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/veins/src/cli/key_cmd.sx+++ /dev/null@@ -1,91 +0,0 @@-/// `vn key`: manage local Ed25519 keys.--val stdio = use("std/stdio")-val str = use("std/string")-val bytes = use("../core/bytes.sx")-val keys = use("../auth/keys.sx")-val ed = use("../crypto/ed25519.sx")-val cmsg = use("../core/msg.sx")--fn print_key(k: keys.Key) void = trust {- val pub_text: bytes.Bytes = ed.format_public(k.public_key)- stdio.print("name: {s}\n", {str.view(k.name.ptr, k.name.len as i64)})- stdio.print("public key: {s}\n", {str.view(pub_text.ptr, pub_text.len as i64)})- stdio.print("fingerprint: {s}\n", {str.view(k.fingerprint.ptr, k.fingerprint.len as i64)})- bytes.free_owned(pub_text)-}--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 => {- cmsg.error_prefix()- stdio.eprint("expected key subcommand (generate, list, show, import)\n", {})- return 1- }- }- if @strcmp(sub, c"generate") == 0 {- val name_opt = @get(args, start + 1)- val name: mut bytes.Bytes = bytes.empty()- if name_opt is some nv {- name = bytes.from_cstr(nv)- } else {- cmsg.error_prefix()- stdio.eprint("key generate requires a name\n", {})- return 1- }- val k_opt = keys.generate(name)- if k_opt is some k {- print_key(k)- keys.free_key(k)- return 0- }- cmsg.error_prefix()- stdio.eprint("cannot create key\n", {})- return 1- }- if @strcmp(sub, c"list") == 0 {- val names: list[bytes.Bytes] = keys.list_names()- for n in names {- val k_opt = keys.load(n)- if k_opt is some k {- print_key(k)- keys.free_key(k)- }- }- keys.free_names(names)- return 0- }- if @strcmp(sub, c"show") == 0 {- val name_opt = @get(args, start + 1)- val name: mut bytes.Bytes = bytes.empty()- if name_opt is some nv {- name = bytes.from_cstr(nv)- } else {- cmsg.error_prefix()- stdio.eprint("key show requires a name\n", {})- return 1- }- val k_opt = keys.load(name)- if k_opt is some k {- print_key(k)- keys.free_key(k)- return 0- }- cmsg.error_prefix()- stdio.eprint("key not found or has unsafe permissions\n", {})- return 1- }- if @strcmp(sub, c"import") == 0 {- cmsg.error_prefix()- stdio.eprint("OpenSSH key import is not supported\n", {})- return 1- }- cmsg.error_prefix()- stdio.eprint("unknown key subcommand: {s}\n", {str.from_cstr(sub)})- return 1-}--- a/veins/src/cli/log_cmd.sx+++ /dev/null@@ -1,405 +0,0 @@-/// `vn log [-rev <revset>] [-lN | -fN]`: 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,- limit: usize,- first: 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)- if limit > 0 {- val shown: mut list[ref LogRec] = lists.new[ref LogRec]()- val n: usize = @len(recs)- if first {- val start: mut usize = 0- if n > limit {- start = n - limit- }- val i: mut usize = n- for i > start {- i--- @append(shown, rec_at(recs, i))- }- } else {- val count: mut usize = n- if count > limit {- count = limit- }- val i: mut usize = 0- for i < count {- @append(shown, rec_at(recs, i))- i++- }- }- @listfree(recs)- recs = shown- }- 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/veins/src/cli/ls_cmd.sx+++ /dev/null@@ -1,352 +0,0 @@-/// `vn ls [rev]`: print the tracked file tree.-///-/// The working copy is snapshotted first, like every command that reads it.-/// Subtrees become directories in the printed tree; files, symlinks, and-/// submodules are leaves.--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 objid = use("../object/id.sx")-val tree = use("../object/tree.sx")-val graph = use("../object/graph.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 snapshot = use("../worktree/snapshot.sx")--fn cmd_is(a: ref u8, text: ref u8, len: usize) bool = trust {- 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 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 free_id(id: objid.Id) void = trust {- if id.ptr != none {- val p: mut ref void = id.ptr as ref void- @free(p)- }-}--/// Concatenate two byte spans into a NUL-terminated buffer. The length in the-/// returned value excludes the terminator.-fn concat(a: bytes.Bytes, b: bytes.Bytes) bytes.Bytes = trust {- val out: ref u8 = @alloc(a.len + b.len + 1) as ref u8- if a.len > 0 {- @memcpy(out as ref void, a.ptr as ref void, a.len)- }- if b.len > 0 {- @memcpy(@ptradd(out, a.len as i64) as ref void, b.ptr as ref void, b.len)- }- @store8(@ptradd(out, (a.len + b.len) as i64), 0)- return bytes.bytes(out, a.len + b.len)-}--fn print_line(prefix: bytes.Bytes, connector: bytes.Bytes, name: bytes.Bytes) void = trust {- val line: mut buf.Buf = buf.new(prefix.len + connector.len + name.len + 1)- buf.Buf.put_bytes(line, prefix)- buf.Buf.put_bytes(line, connector)- buf.Buf.put_bytes(line, name)- buf.Buf.put_u8(line, 0)- stdio.print("{s}\n", {str.from_cstr(line.ptr)})- buf.Buf.free(line)-}--fn join_path(prefix: bytes.Bytes, name: bytes.Bytes) bytes.Bytes = trust {- if prefix.len == 0 {- return concat(bytes.empty(), name)- }- val out: ref u8 = @alloc(prefix.len + 1 + name.len + 1) as ref u8- @memcpy(out as ref void, prefix.ptr as ref void, prefix.len)- @store8(@ptradd(out, prefix.len as i64), 47)- if name.len > 0 {- @memcpy(@ptradd(out, (prefix.len + 1) as i64) as ref void, name.ptr as ref void, name.len)- }- @store8(@ptradd(out, (prefix.len + 1 + name.len) as i64), 0)- return bytes.bytes(out, prefix.len + 1 + name.len)-}--fn collect_plain(- handles: list[ref store.Handle],- tree_id: objid.Id,- prefix: bytes.Bytes,- out: mut list[bytes.Bytes],- depth: usize-) bool = trust {- if depth > 4096 {- return false- }- val t_opt = treewalk.read_tree(handles, tree_id)- val t: mut ref tree.Tree = none- match t_opt {- some x => {- t = x- }- none => {- return false- }- }- val i: mut usize = 0- for i < @len(t.entries) {- val e_opt = @get(t.entries, i)- if e_opt is some e {- val full: bytes.Bytes = join_path(prefix, e.name)- if e.kind == tree.KIND_SUBTREE {- val good: bool = collect_plain(handles, e.target, full, out, depth + 1)- val fp: mut ref void = full.ptr as ref void- @free(fp)- if !good {- tree.free_tree(t)- return false- }- } else {- @append(out, full)- }- }- i++- }- tree.free_tree(t)- return true-}--fn sort_paths(xs: mut list[bytes.Bytes]) void = trust {- val i: mut usize = 1- for i < @len(xs) {- val cur = @get(xs, i)- val c: mut bytes.Bytes = bytes.empty()- 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 bytes.Bytes = bytes.empty()- if prev_opt is some v2 {- prev = v2- }- if bytes.Bytes.cmp(prev, c) <= 0 {- break- }- @set(xs, j, prev)- j--- }- @set(xs, j, c)- i++- }-}--fn free_paths(xs: list[bytes.Bytes]) void = trust {- for p in xs {- if p.ptr != none {- val pp: mut ref void = p.ptr as ref void- @free(pp)- }- }- @listfree(xs)-}--fn print_tree(- handles: list[ref store.Handle],- tree_id: objid.Id,- prefix: bytes.Bytes,- depth: usize-) bool = trust {- if depth > 4096 {- return false- }- val t_opt = treewalk.read_tree(handles, tree_id)- val t: mut ref tree.Tree = none- match t_opt {- some x => {- t = x- }- none => {- return false- }- }- val n: usize = @len(t.entries)- val i: mut usize = 0- for i < n {- val e_opt = @get(t.entries, i)- if e_opt is some e {- val last: bool = i + 1 == n- val connector: mut bytes.Bytes = bytes.bytes(c"|-- ", 4)- if last {- connector = bytes.bytes(c"`-- ", 4)- }- print_line(prefix, connector, e.name)- if e.kind == tree.KIND_SUBTREE {- val add: mut bytes.Bytes = bytes.bytes(c"| ", 4)- if last {- add = bytes.bytes(c" ", 4)- }- val child_prefix: bytes.Bytes = concat(prefix, add)- val good: bool = print_tree(handles, e.target, child_prefix, depth + 1)- val cpp: mut ref void = child_prefix.ptr as ref void- @free(cpp)- if !good {- tree.free_tree(t)- return false- }- }- }- i++- }- tree.free_tree(t)- return true-}--pub fn run(args: list[ref u8], start: usize) i32 = trust {- val rev: mut bytes.Bytes = bytes.empty()- val plain: 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"-plain", 6) || cmd_is(a, c"-p", 2)) {- plain = 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 && 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 = layout.discover(str.from_cstr(c"."))- 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\n", {})- return 1- }- }-- val snap: i32 = snapshot.run(repo)- if snap != 0 {- layout.free_repo(repo)- 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 => {- msg.error_prefix()- stdio.eprint("no operation state\n", {})- store.close(st)- layout.free_repo(repo)- return 1- }- }- val resolved = graph.resolve(st.handles, v, rev)- val target: mut objid.Id = objid.id_none()- val have_target: mut bool = false- if resolved is some id {- target = copy_id(id)- have_target = true- }- view.free_view(v)- if !have_target {- msg.error_prefix()- if rev.len == 0 {- stdio.eprint("no working-copy commit\n", {})- } else {- stdio.eprint("unknown revision: {s}\n", {str.view(rev.ptr, rev.len as i64)})- }- store.close(st)- layout.free_repo(repo)- return 1- }- val lc_opt = graph.load_commit(st.handles, target)- val root: mut objid.Id = objid.id_none()- val have_root: mut bool = false- if lc_opt is some lc {- root = copy_id(lc.c.root_tree)- have_root = true- graph.free_loaded(lc)- }- if !have_root {- msg.error_prefix()- stdio.eprint("cannot read commit\n", {})- free_id(target)- store.close(st)- layout.free_repo(repo)- return 1- }-- val good: mut bool = false- if plain {- val paths: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()- good = collect_plain(st.handles, root, bytes.empty(), paths, 0)- if good {- sort_paths(paths)- for p in paths {- stdio.print("{s}\n", {str.from_cstr(p.ptr)})- }- }- free_paths(paths)- } else {- stdio.print(".\n", {})- good = print_tree(st.handles, root, bytes.empty(), 0)- }- if !good {- msg.error_prefix()- stdio.eprint("cannot read tree\n", {})- }- free_id(root)- free_id(target)- store.close(st)- layout.free_repo(repo)- if !good {- return 1- }- return 0-}--- a/veins/src/cli/merge_cmd.sx+++ /dev/null@@ -1,700 +0,0 @@-/// `vn merge` and `vn rebase`.-///-/// A merge never fails: it records a commit whose tree may contain conflict-/// entries. Rebase rewrites the source and all descendants in one operation.--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 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 txnmod = use("../store/txn.sx")-val viewops = use("../store/viewops.sx")-val view = use("../object/view.sx")-val identity = use("../core/identity.sx")-val repoconfig = use("../core/repoconfig.sx")-val snapshot = use("../worktree/snapshot.sx")-val checkout = use("../worktree/checkout.sx")-val gitmap = use("../git/map.sx")-val object = use("../git/object.sx")-val files = use("../io/files.sx")-val rename = use("../merge/rename.sx")-val engine = use("../merge/engine.sx")-val treemerge = use("../merge/treemerge.sx")--type GitSource = {- repo: mut object.GitRepo- open: mut bool-}--fn open_git(repo: layout.Repo) GitSource = trust {- val p: str.StringView = layout.git_dir(repo)- val r = object.open(p)- val g: mut GitSource = GitSource{repo: @zeroed, open: false}- match r {- ok x => {- g.repo = x- g.open = true- }- err _ => {- files.free_path(p)- }- }- return g-}--fn close_git(g: mut GitSource) void = trust {- if g.open {- object.free(g.repo)- g.open = false- }-}--fn adjacent_config(repo: layout.Repo) bool = trust {- val v = repoconfig.get(repo, bytes.bytes(c"merge.adjacent", 14))- if v is some value {- val on: bool = bytes.Bytes.eql(value, bytes.bytes(c"merge", 5))- files.free_buffer(value)- return on- }- return false-}--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 free_id(id: objid.Id) void = trust {- if id.ptr != none {- val p: mut ref void = id.ptr as ref void- @free(p)- }-}--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 mapped(- old_ids: list[objid.Id],- new_ids: list[objid.Id],- id: objid.Id-) option[objid.Id] = trust {- val i: mut usize = 0- for i < @len(old_ids) {- val o = @get(old_ids, i)- if o is some old {- if objid.Id.eql(old, id) {- val n = @get(new_ids, i)- if n is some nid {- return some nid- }- }- }- i++- }- return none-}--fn mapped_tree(- old_ids: list[objid.Id],- new_trees: list[objid.Id],- id: objid.Id-) option[objid.Id] = trust {- val i: mut usize = 0- for i < @len(old_ids) {- val o = @get(old_ids, i)- if o is some old {- if objid.Id.eql(old, id) {- val t = @get(new_trees, i)- if t is some tid {- return some tid- }- }- }- i++- }- return none-}--fn append_tree(out: mut list[objid.Id], t: option[objid.Id]) void = trust {- if t is some tid {- @append(out, copy_id(tid))- } else {- @append(out, objid.id(none))- }-}--fn text_args(revs: list[bytes.Bytes]) bytes.Bytes = trust {- val b: mut buf.Buf = buf.new(64)- val i: mut usize = 0- for i < @len(revs) {- if i > 0 {- buf.Buf.put_u8(b, 32)- }- val o = @get(revs, 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 desc_with_rerere(prefix: bytes.Bytes, rerere: usize) bytes.Bytes = trust {- if rerere == 0 {- return bytes.Bytes.dup(prefix)- }- val b: mut buf.Buf = buf.new(prefix.len + 32)- buf.Buf.put_bytes(b, prefix)- buf.Buf.put_bytes(b, bytes.from_cstr(c" (rerere"))- // A decimal via formatting keeps the description textual.- val tmp: ref u8 = @fmtalloc(" {d})", {rerere})- buf.Buf.put_bytes(b, bytes.from_cstr(tmp))- @free(tmp as ref void)- val out: bytes.Bytes = bytes.Bytes.dup(buf.Buf.view(b))- buf.Buf.free(b)- return out-}--fn exact_renames_for_parents(- tx: ref txnmod.Txn,- handles: list[ref store.Handle],- git: ref object.GitRepo,- has_git: bool,- parents: list[objid.Id],- merged_tree: objid.Id-) list[ref commit.Rename] = trust {- val out: mut list[ref commit.Rename] = lists.new[ref commit.Rename]()- val i: mut usize = 0- for i < @len(parents) {- val p = @get(parents, i)- if p is some pid {- val pt = engine.tree_of(handles, pid)- val rs = rename.detect_tx(- handles,- git,- has_git,- pt,- some merged_tree,- 0,- i as u64,- tx- )- for r in rs {- @append(out, r)- }- @listfree(rs)- if pt is some tid {- free_id(tid)- }- }- i++- }- return out-}--fn make_commit(- tx: mut ref txnmod.Txn,- handles: list[ref store.Handle],- git: ref object.GitRepo,- has_git: bool,- repo: layout.Repo,- parents: list[objid.Id],- root: objid.Id,- change: objid.ChangeId,- author: prim.Sig,- message: bytes.Bytes,- renames_state: u8,- extra: list[ref prim.KeyValue]-) objid.Id = trust {- val sig: prim.Sig = identity.signature(repo)- val parents_copy: mut list[objid.Id] = lists.new[objid.Id]()- for p in parents {- @append(parents_copy, copy_id(p))- }- val renames: mut list[ref commit.Rename] = lists.new[ref commit.Rename]()- if renames_state == commit.RENAMES_RECORDED {- val detected: list[ref commit.Rename] = exact_renames_for_parents(- tx,- handles,- git,- has_git,- parents,- root- )- for r in detected {- @append(renames, r)- }- @listfree(detected)- }- val nc: mut ref commit.Commit = @alloc(@sizeof(commit.Commit)) as ref commit.Commit- nc.version = 1- nc.parents = parents_copy- nc.root_tree = copy_id(root)- nc.change_id = change- nc.author = author- nc.committer = sig- nc.message = message- nc.renames_state = renames_state- nc.renames = renames- nc.extra = extra- val body: bytes.Bytes = commit.encode(nc)- val id: objid.Id = txnmod.add_object(tx, types.COMMIT, body)- @listfree(parents_copy)- for e in renames {- if e.from_path.ptr != none {- val fp: mut ref void = e.from_path.ptr as ref void- @free(fp)- }- if e.to_path.ptr != none {- val tp: mut ref void = e.to_path.ptr as ref void- @free(tp)- }- val rp: mut ref void = e as ref void- @free(rp)- }- @listfree(renames)- free_id(nc.root_tree)- @free(nc as ref void)- identity.free_sig(sig)- return id-}--pub fn merge(repo: layout.Repo, revs: list[bytes.Bytes]) i32 = trust {- if @len(revs) == 0 {- msg.error_prefix()- stdio.eprint("merge requires at least one revision\n", {})- return 1- }- val snap: i32 = snapshot.run(repo)- if snap != 0 {- return snap- }- val tx_opt = txnmod.begin(repo)- val tx: mut ref txnmod.Txn = none- match tx_opt {- some t => {- tx = t- }- none => {- msg.error_prefix()- stdio.eprint("cannot load repository state\n", {})- return 1- }- }- txnmod.enable_chunk_cache(tx)- val st: store.Store = store.open_all(repo)- val wc_opt = viewops.working_copy(tx.view)- val wc: mut objid.Id = objid.id_none()- if wc_opt is some id {- wc = id- }- if objid.Id.is_none(wc) {- msg.error_prefix()- stdio.eprint("no working-copy commit to merge into\n", {})- store.close(st)- txnmod.abort(tx)- return 1- }- val parents: mut list[objid.Id] = lists.new[objid.Id]()- @append(parents, copy_id(wc))- val i: mut usize = 0- val failed: mut bool = false- for i < @len(revs) {- val o = @get(revs, i)- val rev: mut bytes.Bytes = bytes.empty()- if o is some v {- rev = v- }- val resolved = graph.resolve(st.handles, tx.view, rev)- if resolved is some rid {- if objid.Id.eql(rid, wc) {- msg.error_prefix()- stdio.eprint("cannot merge a commit with itself\n", {})- failed = true- } else {- @append(parents, copy_id(rid))- }- } else {- failed = true- }- i++- }- if failed {- msg.error_prefix()- stdio.eprint("unknown revision\n", {})- graph.free_ids(parents)- store.close(st)- txnmod.abort(tx)- return 1- }- val old_root: option[objid.Id] = engine.tree_of(st.handles, wc)- val git: mut GitSource = open_git(repo)- val outcome: treemerge.Outcome = engine.merge_many(- repo,- tx,- st.handles,- git.repo,- git.open,- parents,- adjacent_config(repo)- )- val cid: ref u8 = @alloc(16) as ref u8- random.random_bytes(cid as ref void, 16)- val author: prim.Sig = identity.signature(repo)- val renames_state: u8 = commit.RENAMES_RECORDED- val extra: list[ref prim.KeyValue] = lists.new[ref prim.KeyValue]()- val new_id: objid.Id = make_commit(- tx,- st.handles,- git.repo,- git.open,- repo,- parents,- outcome.tree,- objid.change_id(cid),- author,- bytes.empty(),- renames_state,- extra- )- viewops.remove_head(tx.view, wc)- viewops.move_bookmarks(tx.view, wc, new_id)- viewops.set_workspace(tx.view, new_id)- viewops.rebuild_heads(tx.view)- val desc_text: bytes.Bytes = text_args(revs)- val b: mut buf.Buf = buf.new(32)- buf.Buf.put_raw(b, c"merge", 5)- if desc_text.len > 0 {- buf.Buf.put_u8(b, 32)- buf.Buf.put_bytes(b, desc_text)- }- val desc: bytes.Bytes = desc_with_rerere(buf.Buf.view(b), outcome.rerere)- val status: i32 = txnmod.finish(tx, desc)- if status == 0 {- val _ = gitmap.mark_native(repo, new_id)- if old_root is some oroot {- val st2: store.Store = store.open_all(repo)- val ms: i32 = checkout.materialize_commit(repo, st2.handles, some oroot, outcome.tree)- store.close(st2)- if ms != 0 {- store.close(st)- close_git(git)- @listfree(parents)- @listfree(extra)- free_id(new_id)- free_id(outcome.tree)- free_id(wc)- free_id(oroot)- @free(cid as ref void)- identity.free_sig(author)- buf.Buf.free(b)- return ms- }- }- }- store.close(st)- close_git(git)- @listfree(parents)- @listfree(extra)- free_id(new_id)- free_id(outcome.tree)- free_id(wc)- if old_root is some oroot2 {- free_id(oroot2)- }- @free(cid as ref void)- identity.free_sig(author)- buf.Buf.free(b)- return status-}--fn map_list(- old_ids: list[objid.Id],- new_ids: list[objid.Id],- ids: mut list[objid.Id]-) void = trust {- val i: mut usize = 0- for i < @len(ids) {- val o = @get(ids, i)- if o is some id {- val m = mapped(old_ids, new_ids, id)- if m is some nid {- @set(ids, i, copy_id(nid))- }- }- i++- }-}--fn remap_view(- v: ref view.View,- old_ids: list[objid.Id],- new_ids: list[objid.Id]-) void = trust {- for bm in v.bookmarks {- val bmm: mut ref view.Bookmark = bm- map_list(old_ids, new_ids, bmm.targets.adds)- map_list(old_ids, new_ids, bmm.targets.removes)- }- for t in v.tags {- val tm: mut ref view.TagRef = t- val m = mapped(old_ids, new_ids, tm.target)- if m is some nid {- tm.target = copy_id(nid)- }- }- val i: mut usize = 0- for i < @len(v.working_copies) {- val o = @get(v.working_copies, i)- if o is some w {- val m2 = mapped(old_ids, new_ids, w.target)- if m2 is some nid2 {- w.target = copy_id(nid2)- }- }- i++- }-}--pub fn rebase(repo: layout.Repo, source: bytes.Bytes, dest: bytes.Bytes) i32 = trust {- val snap: i32 = snapshot.run(repo)- if snap != 0 {- return snap- }- val tx_opt = txnmod.begin(repo)- val tx: mut ref txnmod.Txn = none- match tx_opt {- some t => {- tx = t- }- none => {- msg.error_prefix()- stdio.eprint("cannot load repository state\n", {})- return 1- }- }- txnmod.enable_chunk_cache(tx)- val st: store.Store = store.open_all(repo)- val src_opt = graph.resolve(st.handles, tx.view, source)- val dst_opt = graph.resolve(st.handles, tx.view, dest)- val src: mut objid.Id = objid.id_none()- val dst: mut objid.Id = objid.id_none()- if src_opt is some s {- src = copy_id(s)- }- if dst_opt is some d {- dst = copy_id(d)- }- if objid.Id.is_none(src) || objid.Id.is_none(dst) {- msg.error_prefix()- stdio.eprint("unknown revision\n", {})- store.close(st)- txnmod.abort(tx)- return 1- }- val wc_opt = viewops.working_copy(tx.view)- val wc: mut objid.Id = objid.id_none()- if wc_opt is some wid {- wc = wid- }- val old_wc_root: mut option[objid.Id] = none- if !objid.Id.is_none(wc) {- old_wc_root = engine.tree_of(st.handles, wc)- }-- val all: list[objid.Id] = graph.all(st.handles, tx.view)- val set: mut list[objid.Id] = lists.new[objid.Id]()- for c in all {- if engine.is_ancestor(st.handles, src, c) {- @append(set, copy_id(c))- }- }- val git: mut GitSource = open_git(repo)- val old_ids: mut list[objid.Id] = lists.new[objid.Id]()- val new_ids: mut list[objid.Id] = lists.new[objid.Id]()- val new_tree_ids: mut list[objid.Id] = lists.new[objid.Id]()- val remaining: mut list[objid.Id] = lists.new[objid.Id]()- for c in set {- @append(remaining, copy_id(c))- }- val rerere_total: mut usize = 0- for @len(remaining) > 0 {- val ready_idx: mut i32 = -1- val ri: mut usize = 0- for ri < @len(remaining) {- val ro = @get(remaining, ri)- if ro is some cid {- val parents = engine.parents_of(st.handles, cid)- val ready: mut bool = true- for p in parents {- if contains(set, p) && !contains(old_ids, p) && !objid.Id.eql(cid, src) {- ready = false- }- }- graph.free_ids(parents)- if ready {- ready_idx = ri as i32- break- }- }- ri++- }- if ready_idx < 0 {- msg.error_prefix()- stdio.eprint("rebase could not order commits\n", {})- break- }- val chosen_o = @get(remaining, ready_idx as usize)- val chosen: mut objid.Id = objid.id_none()- if chosen_o is some c {- chosen = c- }- // Rewrite one commit.- val lc_opt = graph.load_commit(st.handles, chosen)- if lc_opt is none {- break- }- val lc: mut ref graph.LoadedCommit = none- if lc_opt is some l {- lc = l- }- val new_parents: mut list[objid.Id] = lists.new[objid.Id]()- val new_parent_trees: mut list[objid.Id] = lists.new[objid.Id]()- val pi: mut usize = 0- for pi < @len(lc.c.parents) {- val po = @get(lc.c.parents, pi)- if po is some p {- if pi == 0 && objid.Id.eql(chosen, src) {- @append(new_parents, copy_id(dst))- append_tree(new_parent_trees, engine.tree_of(st.handles, dst))- } else {- val m = mapped(old_ids, new_ids, p)- if m is some nid {- @append(new_parents, copy_id(nid))- val mt = mapped_tree(old_ids, new_tree_ids, p)- if mt is some tid {- @append(new_parent_trees, copy_id(tid))- } else {- append_tree(new_parent_trees, engine.tree_of(st.handles, p))- }- } else {- @append(new_parents, copy_id(p))- append_tree(new_parent_trees, engine.tree_of(st.handles, p))- }- }- }- pi++- }- if @len(lc.c.parents) == 0 {- @append(new_parents, copy_id(dst))- append_tree(new_parent_trees, engine.tree_of(st.handles, dst))- }- val outcome = engine.rewrite_tree(- repo,- tx,- st.handles,- git.repo,- git.open,- chosen,- lc.c.root_tree,- lc.c.parents,- new_parents,- new_parent_trees,- adjacent_config(repo)- )- rerere_total = rerere_total + outcome.rerere- val new_id: objid.Id = make_commit(- tx,- st.handles,- git.repo,- git.open,- repo,- new_parents,- outcome.tree,- lc.c.change_id,- lc.c.author,- lc.c.message,- lc.c.renames_state,- lc.c.extra- )- @append(old_ids, copy_id(chosen))- @append(new_ids, copy_id(new_id))- @append(new_tree_ids, copy_id(outcome.tree))- graph.free_loaded(lc)- graph.free_ids(new_parent_trees)- @listfree(new_parents)- free_id(outcome.tree)- free_id(new_id)- // Remove the processed commit.- val removed = @remove(remaining, ready_idx as usize)- if removed is some rid {- val _ = rid- }- }- remap_view(tx.view, old_ids, new_ids)- viewops.rebuild_heads(tx.view)- val prefix: mut buf.Buf = buf.new(64)- buf.Buf.put_raw(prefix, c"rebase ", 7)- buf.Buf.put_bytes(prefix, source)- buf.Buf.put_raw(prefix, c" onto ", 6)- buf.Buf.put_bytes(prefix, dest)- val desc: bytes.Bytes = desc_with_rerere(buf.Buf.view(prefix), rerere_total)- val status: mut i32 = txnmod.finish(tx, desc)- if status == 0 {- for nid in new_ids {- val _ = gitmap.mark_native(repo, nid)- }- val mapped_wc = mapped(old_ids, new_ids, wc)- if mapped_wc is some nwc {- val st2: store.Store = store.open_all(repo)- val nr = engine.tree_of(st2.handles, nwc)- if nr is some new_root {- val ms: i32 = checkout.materialize_commit(repo, st2.handles, old_wc_root, new_root)- if ms != 0 {- status = ms- }- free_id(new_root)- }- store.close(st2)- }- }- store.close(st)- close_git(git)- graph.free_ids(all)- graph.free_ids(set)- graph.free_ids(old_ids)- graph.free_ids(new_ids)- graph.free_ids(new_tree_ids)- graph.free_ids(remaining)- free_id(src)- free_id(dst)- free_id(wc)- if old_wc_root is some owr {- free_id(owr)- }- buf.Buf.free(prefix)- return status-}--- a/veins/src/cli/mv_cmd.sx+++ /dev/null@@ -1,136 +0,0 @@-/// `vn mv`: move a tracked file. The following snapshot records the rename.--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 files = use("../io/files.sx")-val stat = use("../io/stat.sx")-val pathspec = use("../worktree/pathspec.sx")-val snapshot = use("../worktree/snapshot.sx")--fn normalize(repo: layout.Repo, arg: bytes.Bytes) option[bytes.Bytes] = trust {- val cwd_opt = pathspec.cwd_relative(repo.root)- val cwd: mut bytes.Bytes = bytes.empty()- if cwd_opt is some c {- cwd = c- }- val norm = pathspec.normalize(repo.root, cwd, arg)- if cwd_opt is some c2 {- files.free_buffer(c2)- }- return norm-}--fn parent_of(path: bytes.Bytes) bytes.Bytes = trust {- val i: mut usize = path.len- for i > 0 {- if bytes.Bytes.at(path, i - 1) == 47 {- return bytes.Bytes.slice(path, 0, i - 1)- }- i--- }- return bytes.empty()-}--pub fn run(repo: layout.Repo, args: list[bytes.Bytes]) i32 = trust {- val snap: i32 = snapshot.run(repo)- if snap != 0 {- return snap- }- if @len(args) != 2 {- msg.error_prefix()- stdio.eprint("mv requires a source and a destination\n", {})- return 1- }- val src_o = @get(args, 0)- val dst_o = @get(args, 1)- val src_arg: mut bytes.Bytes = bytes.empty()- val dst_arg: mut bytes.Bytes = bytes.empty()- if src_o is some s {- src_arg = s- }- if dst_o is some d {- dst_arg = d- }- val src_n = normalize(repo, src_arg)- val dst_n = normalize(repo, dst_arg)- if src_n is none {- msg.error_prefix()- stdio.eprint("invalid path\n", {})- return 1- }- if dst_n is none {- msg.error_prefix()- stdio.eprint("invalid path\n", {})- return 1- }- val src: mut bytes.Bytes = bytes.empty()- val dst: mut bytes.Bytes = bytes.empty()- if src_n is some s2 {- src = s2- }- if dst_n is some d2 {- dst = d2- }- val src_abs: str.StringView = files.join3(- layout.root_view(repo),- str.from_cstr(c""),- files.to_view(src)- )- val dst_abs: str.StringView = files.join3(- layout.root_view(repo),- str.from_cstr(c""),- files.to_view(dst)- )- val src_info = stat.read(src_abs)- if src_info is none {- msg.error_prefix()- stdio.eprint(- "not a tracked path: {s}\n",- {str.view(src.ptr, src.len as i64)}- )- files.free_path(src_abs)- files.free_path(dst_abs)- files.free_buffer(src)- files.free_buffer(dst)- return 1- }- val dst_info = stat.read(dst_abs)- if dst_info is some di {- if di.kind != stat.KIND_MISSING {- msg.error_prefix()- stdio.eprint(- "destination already exists: {s}\n",- {str.view(dst.ptr, dst.len as i64)}- )- files.free_path(src_abs)- files.free_path(dst_abs)- files.free_buffer(src)- files.free_buffer(dst)- return 1- }- }- val parent: bytes.Bytes = parent_of(dst)- if parent.len > 0 {- val parent_abs: str.StringView = files.join3(- layout.root_view(repo),- str.from_cstr(c""),- files.to_view(parent)- )- val _ = files.mkdir_all(parent_abs)- files.free_path(parent_abs)- }- val moved: bool = files.rename_path(src_abs, dst_abs)- files.free_path(src_abs)- files.free_path(dst_abs)- files.free_buffer(src)- files.free_buffer(dst)- if !moved {- msg.error_prefix()- stdio.eprint("cannot move path\n", {})- return 1- }- return snapshot.run(repo)-}--- a/veins/src/cli/new_cmd.sx+++ /dev/null@@ -1,736 +0,0 @@-/// `vn desc` (alias `vn describe`), `vn new`, and `vn go` (alias `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 view = use("../object/view.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 repoconfig = use("../core/repoconfig.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,- st: mut store.Store-) i32 = trust {- val snap: i32 = snapshot.run_with(repo, st)- if snap != 0 {- return snap- }- val message: bytes.Bytes = join_args(args)- val tx_opt = txn.begin_with(repo, st)- 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 handles: list[ref store.Handle] = txn.handles(tx)- val lc_opt = graph.load_commit(handles, wc)- if lc_opt is none {- msg.error_prefix()- stdio.eprint("cannot read working-copy commit\n", {})- 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(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", {})- }- 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- if !changed {- nc.author = 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)- // Repointing a bookmark at the rewritten working-copy commit is what makes- // an edited named branch advance with its commit.- viewops.move_bookmarks(tx.view, wc, new_id)- val current = repoconfig.current_bookmark(repo)- if current is some name {- if viewops.find_bookmark(tx.view, name) is some _ {- viewops.set_bookmark(tx.view, name, new_id)- }- bytes.free_owned(name)- }- 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 {- store.refresh(st, repo)- val _ = gitmap.mark_native(repo, new_id)- }- 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 {- val st: mut store.Store = store.open_all(repo)- val status: i32 = describe_impl(repo, args, false, st)- store.close(st)- return status-}--pub fn commit_changes(repo: layout.Repo, args: list[bytes.Bytes]) i32 = trust {- val st: mut store.Store = store.open_all(repo)- val d: i32 = describe_impl(repo, args, true, st)- if d == NOTHING_TO_COMMIT {- store.close(st)- return 0- }- if d != 0 {- store.close(st)- return d- }- val empty: list[bytes.Bytes] = lists.new[bytes.Bytes]()- val status: i32 = new_change_impl(repo, empty, false, st)- store.close(st)- @listfree(empty)- return status-}--fn free_id(id: objid.Id) void = trust {- if id.ptr != none {- val p: mut ref void = id.ptr as ref void- @free(p)- }-}--fn contains_id(ids: list[objid.Id], id: objid.Id) bool = trust {- for x in ids {- if objid.Id.eql(x, id) {- return true- }- }- return false-}--fn mapped_id(- old_ids: list[objid.Id],- new_ids: list[objid.Id],- id: objid.Id-) option[objid.Id] = trust {- val i: mut usize = 0- for i < @len(old_ids) {- val o = @get(old_ids, i)- if o is some old {- if objid.Id.eql(old, id) {- val n = @get(new_ids, i)- if n is some nid {- return some nid- }- }- }- i++- }- return none-}--fn remap_ids(- old_ids: list[objid.Id],- new_ids: list[objid.Id],- ids: mut list[objid.Id]-) void = trust {- val i: mut usize = 0- for i < @len(ids) {- val o = @get(ids, i)- if o is some id {- val m = mapped_id(old_ids, new_ids, id)- if m is some nid {- @set(ids, i, copy_id(nid))- }- }- i++- }-}--fn remap_amend_view(- v: ref view.View,- old_ids: list[objid.Id],- new_ids: list[objid.Id]-) void = trust {- for bm in v.bookmarks {- val bmm: mut ref view.Bookmark = bm- remap_ids(old_ids, new_ids, bmm.targets.adds)- remap_ids(old_ids, new_ids, bmm.targets.removes)- }- for t in v.tags {- val tm: mut ref view.TagRef = t- val m = mapped_id(old_ids, new_ids, tm.target)- if m is some nid {- tm.target = copy_id(nid)- }- }- for w in v.working_copies {- val wm: mut ref view.WorkspaceRef = w- val m = mapped_id(old_ids, new_ids, wm.target)- if m is some nid {- wm.target = copy_id(nid)- }- }- for rr in v.remote_refs {- val rm: mut ref view.RemoteRef = rr- val m = mapped_id(old_ids, new_ids, rm.target)- if m is some nid {- rm.target = copy_id(nid)- }- }-}--fn amend_ready(- handles: list[ref store.Handle],- cid: objid.Id,- target: objid.Id,- old_ids: list[objid.Id]-) bool = trust {- if objid.Id.eql(cid, target) {- return true- }- val lc_opt = graph.load_commit(handles, cid)- val ready: mut bool = false- if lc_opt is some lc {- for p in lc.c.parents {- if contains_id(old_ids, p) {- ready = true- break- }- }- graph.free_loaded(lc)- }- return ready-}--fn amendment_is_pushed(- handles: list[ref store.Handle],- v: ref view.View,- target: objid.Id-) bool = trust {- val roots: mut list[objid.Id] = lists.new[objid.Id]()- for rr in v.remote_refs {- @append(roots, copy_id(rr.target))- }- val pushed: mut bool = false- if @len(roots) > 0 {- val reachable: list[objid.Id] = graph.collect(handles, roots)- pushed = contains_id(reachable, target)- graph.free_ids(reachable)- }- graph.free_ids(roots)- return pushed-}--fn amend_impl(repo: layout.Repo, rev: bytes.Bytes, message: 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 handles: list[ref store.Handle] = txn.handles(tx)- val target_opt = graph.resolve(handles, tx.view, rev)- val target: mut objid.Id = objid.id_none()- match target_opt {- some tid => {- target = copy_id(tid)- }- none => {- msg.error_prefix()- stdio.eprint("unknown revision\n", {})- txn.abort(tx)- return 1- }- }- if amendment_is_pushed(handles, tx.view, target) {- msg.error_prefix()- stdio.eprint("cannot amend a revision that has been pushed\n", {})- txn.abort(tx)- free_id(target)- return 1- }- val target_lc_opt = graph.load_commit(handles, target)- if target_lc_opt is none {- msg.error_prefix()- stdio.eprint("cannot read revision\n", {})- txn.abort(tx)- free_id(target)- return 1- }- val target_lc: mut ref graph.LoadedCommit = none- if target_lc_opt is some lc {- target_lc = lc- }- val same_message: bool = bytes.Bytes.eql(target_lc.c.message, message)- graph.free_loaded(target_lc)- if same_message {- msg.info_prefix()- stdio.print("message unchanged\n", {})- txn.abort(tx)- free_id(target)- return 0- }- val all: list[objid.Id] = graph.all(handles, tx.view)- val remaining: mut list[objid.Id] = lists.new[objid.Id]()- for c in all {- @append(remaining, copy_id(c))- }- graph.free_ids(all)- val old_ids: mut list[objid.Id] = lists.new[objid.Id]()- val new_ids: mut list[objid.Id] = lists.new[objid.Id]()- val sig: prim.Sig = identity.signature(repo)- val failed: mut bool = false- val done: mut bool = false- val target_rewritten: mut bool = false- for @len(remaining) > 0 && !failed && !done {- val ready_idx: mut i32 = -1- val ri: mut usize = 0- for ri < @len(remaining) {- val ro = @get(remaining, ri)- if ro is some cid {- if amend_ready(handles, cid, target, old_ids) {- ready_idx = ri as i32- break- }- }- ri++- }- if ready_idx < 0 {- done = true- } else {- val chosen_o = @get(remaining, ready_idx as usize)- val chosen: mut objid.Id = objid.id_none()- if chosen_o is some c {- chosen = c- }- val lc_opt = graph.load_commit(handles, chosen)- if lc_opt is none {- failed = true- } else {- val lc: mut ref graph.LoadedCommit = none- if lc_opt is some l {- lc = l- }- val new_parents: mut list[objid.Id] = lists.new[objid.Id]()- for p in lc.c.parents {- val m = mapped_id(old_ids, new_ids, p)- if m is some nid {- @append(new_parents, copy_id(nid))- } else {- @append(new_parents, copy_id(p))- }- }- val nc: mut ref commit.Commit = @alloc(@sizeof(commit.Commit)) as ref commit.Commit- nc.version = lc.c.version- nc.parents = new_parents- nc.root_tree = lc.c.root_tree- nc.change_id = lc.c.change_id- nc.author = lc.c.author- nc.committer = sig- if objid.Id.eql(chosen, target) {- nc.message = message- } else {- nc.message = lc.c.message- }- nc.renames_state = lc.c.renames_state- nc.renames = lc.c.renames- nc.extra = lc.c.extra- val encoded: bytes.Bytes = commit.encode(nc)- val new_id: objid.Id = txn.add_object(tx, types.COMMIT, encoded)- @append(old_ids, copy_id(chosen))- @append(new_ids, copy_id(new_id))- if objid.Id.eql(chosen, target) {- target_rewritten = true- }- graph.free_ids(new_parents)- @free(nc as ref void)- graph.free_loaded(lc)- free_id(new_id)- }- val removed: objid.Id = @remove(remaining, ready_idx as usize)- free_id(removed)- }- }- if failed || !target_rewritten {- msg.error_prefix()- stdio.eprint("cannot amend revision\n", {})- txn.abort(tx)- identity.free_sig(sig)- graph.free_ids(old_ids)- graph.free_ids(new_ids)- graph.free_ids(remaining)- free_id(target)- return 1- }- remap_amend_view(tx.view, old_ids, new_ids)- viewops.rebuild_heads(tx.view)- val desc: mut buf.Buf = buf.new(64)- buf.Buf.put_raw(desc, c"amend ", 6)- buf.Buf.put_bytes(desc, rev)- val status: i32 = txn.finish(tx, buf.Buf.view(desc))- if status == 0 {- for nid in new_ids {- val _ = gitmap.mark_native(repo, nid)- }- }- buf.Buf.free(desc)- identity.free_sig(sig)- graph.free_ids(old_ids)- graph.free_ids(new_ids)- graph.free_ids(remaining)- free_id(target)- return status-}--pub fn amend(repo: layout.Repo, rev: bytes.Bytes, args: list[bytes.Bytes]) i32 = trust {- val message: bytes.Bytes = join_args(args)- val status: i32 = amend_impl(repo, rev, message)- bytes.free_owned(message)- return status-}--fn new_change_impl(- repo: layout.Repo,- revs: list[bytes.Bytes],- do_snapshot: bool,- st: mut store.Store-) i32 = trust {- if do_snapshot {- val snap: i32 = snapshot.run_with(repo, st)- if snap != 0 {- return snap- }- }- val tx_opt = txn.begin_with(repo, st)- 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 handles: list[ref store.Handle] = txn.handles(tx)- 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 old_root: mut option[objid.Id] = none- if have_wc {- val old_lc_opt = graph.load_commit(handles, wc)- if old_lc_opt is some old_lc {- old_root = some(copy_id(old_lc.c.root_tree))- graph.free_loaded(old_lc)- }- }- 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", {})- txn.abort(tx)- return 1- }- val lc_opt = graph.load_commit(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", {})- 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(handles, tx.view, rev)- match resolved {- some id => {- @append(parents, copy_id(id))- if i == 0 {- val lc_opt = graph.load_commit(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", {})- 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: mut i32 = txn.finish(tx, bytes.bytes(c"new", 3))- if status == 0 {- store.refresh(st, repo)- val _ = gitmap.mark_native(repo, new_id)- if @len(revs) > 0 {- // The new commit was created from the requested revision, but the- // files on disk still belong to the previous working-copy commit.- status = checkout.materialize_commit(repo, st.handles, old_root, root_tree)- }- }- @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)- }- if old_root is some oroot {- if oroot.ptr != none {- val orp: mut ref void = oroot.ptr as ref void- @free(orp)- }- }- identity.free_sig(sig)- return status-}--pub fn new_change(repo: layout.Repo, revs: list[bytes.Bytes]) i32 = trust {- val st: mut store.Store = store.open_all(repo)- val status: i32 = new_change_impl(repo, revs, true, st)- store.close(st)- return status-}--- a/veins/src/cli/op_cmd.sx+++ /dev/null@@ -1,386 +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 graph = use("../object/graph.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")-val viewops = use("../store/viewops.sx")-val checkout = use("../worktree/checkout.sx")-val snapshot = use("../worktree/snapshot.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 wc_tree(- handles: list[ref store.Handle],- v: ref view.View-) option[objid.Id] = trust {- val wc_opt = viewops.working_copy(v)- val out: mut option[objid.Id] = none- if wc_opt is some wc {- val lc_opt = graph.load_commit(handles, wc)- if lc_opt is some lc {- out = some(graph.copy_id(lc.c.root_tree))- graph.free_loaded(lc)- }- if wc.ptr != none {- val wp: mut ref void = wc.ptr as ref void- @free(wp)- }- }- 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)- }- }-}--fn write_view(- repo: layout.Repo,- handles: list[ref store.Handle],- 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- }- }- val old_tree: option[objid.Id] = wc_tree(handles, tx.view)- val new_tree: option[objid.Id] = wc_tree(handles, new_view)- view.free_view(tx.view)- tx.view = new_view- val status: mut i32 = txn.finish(tx, description)- if status == 0 {- val synced: i32 = checkout.materialize_optional(repo, handles, old_tree, new_tree)- if synced != 0 {- status = synced- }- }- free_tree_opt(old_tree)- free_tree_opt(new_tree)- return status-}--pub fn restore(repo: layout.Repo, text: bytes.Bytes) i32 = trust {- val snap: i32 = snapshot.run(repo)- if snap != 0 {- return snap- }- 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, st.handles, 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 snap: i32 = snapshot.run(repo)- if snap != 0 {- return snap- }- 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, st.handles, tv, bytes.bytes(c"op revert", 9))- }- operation.free_operation(parent)- }- }- } else {- val empty: ref view.View = state.empty_view()- status = write_view(repo, st.handles, 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 snap: i32 = snapshot.run(repo)- if snap != 0 {- return snap- }- 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, st.handles, 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/veins/src/cli/push_cmd.sx+++ /dev/null@@ -1,306 +0,0 @@-/// `vn push`: native push.--val stdio = use("std/stdio")-val str = use("std/string")-val bytes = use("../core/bytes.sx")-val lists = use("../core/lists.sx")-val objid = use("../object/id.sx")-val graph = use("../object/graph.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 remote_config = use("../git/remote.sx")-val repoconfig = use("../core/repoconfig.sx")-val credentials = use("../auth/credentials.sx")-val client = use("../protocol/client.sx")-val transfer = use("../protocol/transfer.sx")-val msg_refs = use("../protocol/messages.sx")-val cmsg = use("../core/msg.sx")--fn target_matches(target: objid.Id, old: bytes.Bytes) bool = {- if old.len != 32 {- return false- }- return bytes.Bytes.eql(bytes.bytes(target.ptr, 32), old)-}--fn report_client_error(c: ref client.Client, context: bytes.Bytes) void = trust {- val detail: bytes.Bytes = client.error_text(c)- cmsg.error_prefix()- if detail.len > 0 {- stdio.eprint("{s}: {s}\n", {- str.view(context.ptr, context.len as i64),- str.view(detail.ptr, detail.len as i64)- })- } else {- stdio.eprint("{s}\n", {str.view(context.ptr, context.len as i64)})- }- bytes.free_owned(detail)-}--fn find_server_target(refs: list[msg_refs.RefInfo], name: bytes.Bytes) bytes.Bytes = trust {- for r in refs {- if bytes.Bytes.eql(r.name, name) {- return bytes.Bytes.dup(r.target)- }- }- return bytes.empty()-}--pub fn run(args: list[ref u8], start: usize) i32 = trust {- val remote_name: mut bytes.Bytes = bytes.Bytes.dup(bytes.bytes(c"origin", 6))- val bookmark: mut bytes.Bytes = bytes.empty()- val explicit_key: mut bytes.Bytes = bytes.empty()- val explicit_pin: mut bytes.Bytes = bytes.empty()- val path: mut str.StringView = str.from_cstr(c".")- val have_remote: mut bool = false- 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)- if bytes.Bytes.starts_with(av, bytes.bytes(c"-key:", 5)) {- explicit_key = bytes.Bytes.dup(bytes.Bytes.slice(av, 5, av.len))- if bytes.Bytes.starts_with(explicit_key, bytes.bytes(c"ed25519:", 8)) {- cmsg.error_prefix()- stdio.eprint("-key: expects a local key name, not a public key\n", {})- return 1- }- } elif bytes.Bytes.starts_with(av, bytes.bytes(c"-pin:", 5)) {- explicit_pin = bytes.Bytes.dup(bytes.Bytes.slice(av, 5, av.len))- } elif av.len > 0 && bytes.Bytes.at(av, 0) == 45 {- cmsg.error_prefix()- stdio.eprint("unknown flag: {s}\n", {str.from_cstr(a)})- return 1- } elif !have_remote {- remote_name = bytes.Bytes.dup(av)- have_remote = true- } elif bookmark.ptr == none {- bookmark = bytes.Bytes.dup(av)- } else {- path = str.from_cstr(a)- }- }- i++- }- val repo_opt = layout.discover(path)- val repo: mut layout.Repo = layout.Repo{root: bytes.empty()}- match repo_opt {- some r => {- repo = r- }- none => {- cmsg.error_prefix()- stdio.eprint("not a veins repository\n", {})- return 1- }- }- if bookmark.ptr == none {- val cur = repoconfig.current_bookmark(repo)- if cur is some name {- bookmark = name- }- }- if bookmark.ptr == none {- cmsg.error_prefix()- stdio.eprint("push requires a bookmark name (or a current bookmark)\n", {})- layout.free_repo(repo)- return 1- }- val url_opt = remote_config.url_of(repo, remote_name)- if url_opt is none {- cmsg.error_prefix()- stdio.eprint("unknown remote\n", {})- layout.free_repo(repo)- return 1- }- val url: mut bytes.Bytes = bytes.empty()- match url_opt {- some v => {- url = v- }- none => {- return 1- }- }- val key_name = remote_config.key_name_of(repo, remote_name)- val key: mut bytes.Bytes = bytes.empty()- if explicit_key.ptr != none {- key = explicit_key- } else {- if key_name is some k {- if credentials.local_key_exists(k) {- key = k- } else {- bytes.free_owned(k)- }- }- if key.ptr == none {- val fallback = credentials.key_for_url(url)- if fallback is some ck {- key = ck- }- }- }- val pin_opt = remote_config.tls_pin_of(repo, remote_name)- val pin: mut bytes.Bytes = bytes.empty()- if explicit_pin.ptr != none {- pin = explicit_pin- } else {- if pin_opt is some pv {- pin = pv- }- }- 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 => {- v = state.empty_view()- }- }- val target_opt = graph.resolve(st.handles, v, bookmark)- if target_opt is none {- cmsg.error_prefix()- stdio.eprint("unknown bookmark: {s}\n", {str.view(bookmark.ptr, bookmark.len as i64)})- view.free_view(v)- store.close(st)- layout.free_repo(repo)- return 1- }- val target: mut objid.Id = objid.id_none()- match target_opt {- some tv => {- target = graph.copy_id(tv)- }- none => {- return 1- }- }- val roots: mut list[objid.Id] = lists.new[objid.Id]()- @append(roots, target)- val commits: list[objid.Id] = graph.collect(st.handles, roots)- val objects: list[objid.Id] = transfer.objects_for_commits(st.handles, commits)- @listfree(roots)- view.free_view(v)- store.close(st)- val repo_name: bytes.Bytes = client.url_repo_name(url)- val c_opt = client.connect_pinned(url, key, repo_name, pin)- bytes.free_owned(url)- if key.ptr != none {- bytes.free_owned(key)- }- if repo_name.ptr != none {- bytes.free_owned(repo_name)- }- val c: mut ref client.Client = none- match c_opt {- some x => {- c = x- }- none => {- val detail: bytes.Bytes = client.last_connect_error()- cmsg.error_prefix()- if detail.len > 0 {- stdio.eprint("{s}\n", {str.view(detail.ptr, detail.len as i64)})- } else {- stdio.eprint("cannot connect or authenticate\n", {})- }- bytes.free_owned(detail)- transfer.free_id_bytes(commits)- transfer.free_id_bytes(objects)- layout.free_repo(repo)- return 1- }- }- val refs_opt = client.list_refs(c)- if refs_opt is none {- report_client_error(c, bytes.bytes(c"cannot list remote refs", 23))- client.free_client(c)- transfer.free_id_bytes(commits)- transfer.free_id_bytes(objects)- layout.free_repo(repo)- return 1- }- val old: mut bytes.Bytes = bytes.empty()- if refs_opt is some refs {- old = find_server_target(refs, bookmark)- msg_refs.free_refs(refs)- }- if target_matches(target, old) {- bytes.free_owned(old)- client.free_client(c)- transfer.free_id_bytes(commits)- transfer.free_id_bytes(objects)- layout.free_repo(repo)- cmsg.info_prefix()- stdio.print("nothing to push, everything is up to date\n", {})- bytes.free_owned(bookmark)- bytes.free_owned(remote_name)- return 0- }- if !client.push_objects(c, repo, objects) {- report_client_error(c, bytes.bytes(c"push failed", 11))- client.free_client(c)- transfer.free_id_bytes(commits)- transfer.free_id_bytes(objects)- layout.free_repo(repo)- return 1- }- val updates: mut list[msg_refs.UpdateRef] = lists.new[msg_refs.UpdateRef]()- @append(- updates,- msg_refs.UpdateRef{- name: bytes.Bytes.dup(bookmark),- expected: old,- target: bytes.Bytes.dup(bytes.bytes(target.ptr, 32))- }- )- val pushed: bool = client.update_refs(c, updates)- msg_refs.free_updates(updates)- if !pushed {- report_client_error(c, bytes.bytes(c"ref update rejected", 19))- client.free_client(c)- transfer.free_id_bytes(commits)- transfer.free_id_bytes(objects)- layout.free_repo(repo)- return 1- }- client.free_client(c)- transfer.free_id_bytes(commits)- transfer.free_id_bytes(objects)- layout.free_repo(repo)- cmsg.info_prefix()- stdio.print(- "pushed {s} to {s}\n",- {- str.view(bookmark.ptr, bookmark.len as i64),- str.view(remote_name.ptr, remote_name.len as i64)- }- )- bytes.free_owned(bookmark)- bytes.free_owned(remote_name)- return 0-}--test "remote target comparison" {- trust {- val raw: ref u8 = @alloc(32) as ref u8- val i: mut usize = 0- for i < 32 {- @store8(@ptradd(raw, i as i64), 7)- i++- }- val id: objid.Id = objid.id(raw)- val same: bytes.Bytes = bytes.Bytes.dup(bytes.bytes(raw, 32))- assert target_matches(id, same)- assert !target_matches(id, bytes.empty())- assert !target_matches(id, bytes.bytes(c"short", 5))- bytes.free_owned(same)- @free(raw as ref void)- }-}--- a/veins/src/cli/remote_cmd.sx+++ /dev/null@@ -1,206 +0,0 @@-/// `vn remote`: manage native remotes stored in `.veins/config`.--val stdio = use("std/stdio")-val str = use("std/string")-val bytes = use("../core/bytes.sx")-val msg = use("../core/msg.sx")-val config = use("../core/repoconfig.sx")-val layout = use("../store/layout.sx")-val remote = use("../git/remote.sx")--fn cmd_is(a: ref u8, text: ref u8, len: usize) bool = trust {- return bytes.Bytes.eql(bytes.from_cstr(a), bytes.bytes(text, len))-}--fn set_field(- repo: layout.Repo,- name: bytes.Bytes,- field: ref u8,- field_len: usize,- value: bytes.Bytes-) bool = trust {- val key: bytes.Bytes = remote.key_for(name, bytes.bytes(field, field_len))- val passed: bool = config.set(repo, key, value)- bytes.free_owned(key)- return passed-}--fn clear_field(repo: layout.Repo, name: bytes.Bytes, field: ref u8, field_len: usize) bool = trust {- val key: bytes.Bytes = remote.key_for(name, bytes.bytes(field, field_len))- val passed: bool = config.remove(repo, key)- bytes.free_owned(key)- return passed-}--fn run_upsert(repo: layout.Repo, args: list[ref u8], start: usize, replace: bool) i32 = trust {- val name: mut bytes.Bytes = bytes.empty()- val url: mut bytes.Bytes = bytes.empty()- val key: mut option[bytes.Bytes] = none- val pin: mut option[bytes.Bytes] = 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)- if bytes.Bytes.starts_with(av, bytes.bytes(c"-key:", 5)) {- key = some(bytes.Bytes.slice(av, 5, av.len))- } elif bytes.Bytes.starts_with(av, bytes.bytes(c"-pin:", 5)) {- pin = some(bytes.Bytes.slice(av, 5, av.len))- } 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- } elif name.ptr == none {- name = av- } elif url.ptr == none {- url = av- } else {- msg.error_prefix()- stdio.eprint("too many arguments\n", {})- return 1- }- }- i++- }- if name.ptr == none || url.ptr == none {- msg.error_prefix()- if replace {- stdio.eprint("remote set-url requires a name and URL\n", {})- } else {- stdio.eprint("remote add requires a name and URL\n", {})- }- return 1- }- val existing = remote.url_of(repo, name)- if existing is some old {- bytes.free_owned(old)- if !replace {- msg.error_prefix()- stdio.eprint("remote already exists: {s}\n", {str.view(name.ptr, name.len as i64)})- return 1- }- } elif replace {- msg.error_prefix()- stdio.eprint("unknown remote: {s}\n", {str.view(name.ptr, name.len as i64)})- return 1- }- if !set_field(repo, name, c"url", 3, url) {- msg.error_prefix()- stdio.eprint("cannot write repository config\n", {})- return 1- }- if key is some value {- val passed: mut bool = true- if value.len == 0 {- passed = clear_field(repo, name, c"key", 3)- } else {- passed = set_field(repo, name, c"key", 3, value)- }- if !passed {- msg.error_prefix()- stdio.eprint("cannot write repository config\n", {})- return 1- }- }- if pin is some value {- val passed: mut bool = true- if value.len == 0 {- passed = clear_field(repo, name, c"tls-pin", 7)- } else {- passed = set_field(repo, name, c"tls-pin", 7, value)- }- if !passed {- msg.error_prefix()- stdio.eprint("cannot write repository config\n", {})- return 1- }- }- return 0-}--fn run_list(repo: layout.Repo) i32 = trust {- val names: list[bytes.Bytes] = remote.list_remotes(repo)- for name in names {- val url_opt = remote.url_of(repo, name)- val url: mut bytes.Bytes = bytes.empty()- if url_opt is some value {- url = value- }- stdio.print(- "{s}\t{s}\n",- {str.view(name.ptr, name.len as i64), str.view(url.ptr, url.len as i64)}- )- if url.ptr != none {- bytes.free_owned(url)- }- bytes.free_owned(name)- }- @listfree(names)- return 0-}--fn run_remove(repo: layout.Repo, args: list[ref u8], start: usize) i32 = trust {- val name_opt = @get(args, start)- if name_opt is none {- msg.error_prefix()- stdio.eprint("remote remove requires a name\n", {})- return 1- }- val name: mut bytes.Bytes = bytes.empty()- if name_opt is some n {- name = bytes.from_cstr(n)- }- val existing = remote.url_of(repo, name)- if existing is none {- msg.error_prefix()- stdio.eprint("unknown remote: {s}\n", {str.view(name.ptr, name.len as i64)})- return 1- }- if existing is some old {- bytes.free_owned(old)- }- clear_field(repo, name, c"url", 3)- clear_field(repo, name, c"key", 3)- clear_field(repo, name, c"tls-pin", 7)- return 0-}--pub fn run(args: list[ref u8], start: usize) i32 = trust {- val sub_opt = @get(args, start)- if sub_opt is none {- msg.error_prefix()- stdio.eprint("expected a remote subcommand (add, set-url, list, remove)\n", {})- return 1- }- val sub: mut ref u8 = none- if sub_opt is some s {- sub = s- }- val repo_opt = layout.discover(str.from_cstr(c"."))- val repo: mut layout.Repo = layout.Repo{root: bytes.empty()}- match repo_opt {- some r => {- repo = r- }- none => {- msg.error_prefix()- stdio.eprint("not a veins repository\n", {})- return 1- }- }- val status: mut i32 = 1- if cmd_is(sub, c"add", 3) {- status = run_upsert(repo, args, start + 1, false)- } elif cmd_is(sub, c"set-url", 7) {- status = run_upsert(repo, args, start + 1, true)- } elif cmd_is(sub, c"list", 4) || cmd_is(sub, c"ls", 2) {- status = run_list(repo)- } elif cmd_is(sub, c"remove", 6) || cmd_is(sub, c"rm", 2) {- status = run_remove(repo, args, start + 1)- } else {- msg.error_prefix()- stdio.eprint("unknown remote subcommand: {s}\n", {str.from_cstr(sub)})- }- layout.free_repo(repo)- return status-}--- a/veins/src/cli/resolve_cmd.sx+++ /dev/null@@ -1,784 +0,0 @@-/// `vn xs` and `vn resolve`.--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 types = use("../object/types.sx")-val tree = use("../object/tree.sx")-val commit = use("../object/commit.sx")-val conflict = use("../object/conflict.sx")-val blob = use("../object/blob.sx")-val graph = use("../object/graph.sx")-val treewalk = use("../object/treewalk.sx")-val state = use("../store/state.sx")-val store = use("../store/store.sx")-val layout = use("../store/layout.sx")-val txnmod = use("../store/txn.sx")-val viewops = use("../store/viewops.sx")-val view = use("../object/view.sx")-val identity = use("../core/identity.sx")-val repoconfig = use("../core/repoconfig.sx")-val files = use("../io/files.sx")-val stat = use("../io/stat.sx")-val pathspec = use("../worktree/pathspec.sx")-val snapshot = use("../worktree/snapshot.sx")-val checkout = use("../worktree/checkout.sx")-val treeedit = use("../worktree/treeedit.sx")-val object = use("../git/object.sx")-val raw = use("../object/raw.sx")-val filemerge = use("../merge/filemerge.sx")-val resolutions = use("../merge/resolutions.sx")--extern (C) fn system(command: ref u8) i32 = "system"--type GitSource = {- repo: mut object.GitRepo- open: mut bool-}--fn open_git(repo: layout.Repo) GitSource = trust {- val p: str.StringView = layout.git_dir(repo)- val r = object.open(p)- val g: mut GitSource = GitSource{repo: @zeroed, open: false}- match r {- ok x => {- g.repo = x- g.open = true- }- err _ => {- files.free_path(p)- }- }- return g-}--fn close_git(g: mut GitSource) void = trust {- if g.open {- object.free(g.repo)- g.open = false- }-}--fn adjacent_config(repo: layout.Repo) bool = trust {- val v = repoconfig.get(repo, bytes.bytes(c"merge.adjacent", 14))- if v is some value {- val on: bool = bytes.Bytes.eql(value, bytes.bytes(c"merge", 5))- files.free_buffer(value)- return on- }- return false-}--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 free_id(id: objid.Id) void = trust {- if id.ptr != none {- val p: mut ref void = id.ptr as ref void- @free(p)- }-}--fn wc_tree(- handles: list[ref store.Handle],- v: ref view.View-) option[objid.Id] = trust {- val wc_opt = viewops.working_copy(v)- val out: mut option[objid.Id] = none- if wc_opt is some wc {- val lc_opt = graph.load_commit(handles, wc)- if lc_opt is some lc {- out = some(graph.copy_id(lc.c.root_tree))- graph.free_loaded(lc)- }- free_id(wc)- }- return out-}--fn load_conflict(- handles: list[ref store.Handle],- id: objid.Id-) option[ref conflict.Conflict] = trust {- val body_opt = state.read_body(handles, id, types.CONFLICT)- val body: mut bytes.Bytes = bytes.empty()- match body_opt {- some b => {- body = b- }- none => {- return none- }- }- val decoded = conflict.decode(body)- val out: mut option[ref conflict.Conflict] = none- match decoded {- ok c => {- out = some c- }- err _ => {- }- }- if out is none {- files.free_buffer(body)- }- return out-}--fn kind_label(c: ref conflict.Conflict) str.StringView = trust {- for v in c.adds {- if v.kind == tree.KIND_SUBTREE {- return str.from_cstr(c"tree")- }- }- for v in c.removes {- if v.kind == tree.KIND_SUBTREE {- return str.from_cstr(c"tree")- }- }- for v in c.adds {- if v.kind == 0 {- return str.from_cstr(c"delete/modify")- }- }- for v in c.removes {- if v.kind == 0 {- return str.from_cstr(c"delete/modify")- }- }- return str.from_cstr(c"text")-}--type ConflictItem = {- path: mut bytes.Bytes- target: mut objid.Id-}--fn collect(- handles: list[ref store.Handle],- tree_id: objid.Id-) list[ref ConflictItem] = trust {- val out: mut list[ref ConflictItem] = lists.new[ref ConflictItem]()- val flat: list[ref treewalk.FlatEntry] = treewalk.flatten(handles, tree_id)- for e in flat {- if e.kind == tree.KIND_CONFLICT {- val ci: mut ref ConflictItem = @alloc(@sizeof(ConflictItem)) as ref ConflictItem- ci.path = bytes.Bytes.dup(e.path)- ci.target = copy_id(e.target)- @append(out, ci)- }- }- treewalk.free_flat(flat)- return out-}--fn free_items(xs: list[ref ConflictItem]) void = trust {- for x in xs {- if x.path.ptr != none {- val pp: mut ref void = x.path.ptr as ref void- @free(pp)- }- free_id(x.target)- val xp: mut ref void = x as ref void- @free(xp)- }- @listfree(xs)-}--fn print_range(a: usize, b: usize) void = trust {- if a == b {- stdio.print("{d}", {a + 1})- } else {- stdio.print("{d}-{d}", {a + 1, b})- }-}--fn ranges_of(- handles: list[ref store.Handle],- git: ref object.GitRepo,- has_git: bool,- c: ref conflict.Conflict,- adjacent: bool-) option[filemerge.EditResult] = trust {- if @len(c.adds) != 2 || @len(c.removes) != 1 {- return none- }- val a0 = @get(c.adds, 0)- val a1 = @get(c.adds, 1)- val r0 = @get(c.removes, 0)- if a0 is some ours {- if a1 is some theirs {- if r0 is some base {- if ours.kind == 0 || theirs.kind == 0 || base.kind == 0 {- return none- }- if ours.kind == tree.KIND_SUBTREE- || theirs.kind == tree.KIND_SUBTREE- || base.kind == tree.KIND_SUBTREE {- return none- }- return filemerge.merge_blobs(- handles,- git,- has_git,- base.target,- ours.target,- theirs.target,- adjacent- )- }- }- }- return none-}--pub fn xs(repo: layout.Repo, porcelain: 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- if v_opt is some x {- v = x- } else {- msg.error_prefix()- stdio.eprint("no operation state\n", {})- store.close(st)- return 1- }- val tree_opt = wc_tree(st.handles, v)- val items: mut list[ref ConflictItem] = lists.new[ref ConflictItem]()- if tree_opt is some tid {- items = collect(st.handles, tid)- free_id(tid)- }- val git: mut GitSource = open_git(repo)- val adjacent: bool = adjacent_config(repo)- val first: mut bool = true- for it in items {- val c_opt = load_conflict(st.handles, it.target)- if c_opt is some c {- if porcelain {- stdio.print("{s}\t", {str.view(it.path.ptr, it.path.len as i64)})- stdio.print("{s}\t", {kind_label(c)})- val rr = ranges_of(st.handles, git.repo, git.open, c, adjacent)- if rr is some r {- val i: mut usize = 0- for i < @len(r.ranges) {- val x = @get(r.ranges, i)- if x is some range {- if i > 0 {- stdio.print(",", {})- }- print_range(range.base_start, range.base_end)- }- i++- }- stdio.print("\t", {})- val j: mut usize = 0- for j < @len(r.ranges) {- val x2 = @get(r.ranges, j)- if x2 is some range2 {- if j > 0 {- stdio.print(",", {})- }- print_range(range2.ours_start, range2.ours_end)- }- j++- }- stdio.print("\t", {})- val k: mut usize = 0- for k < @len(r.ranges) {- val x3 = @get(r.ranges, k)- if x3 is some range3 {- if k > 0 {- stdio.print(",", {})- }- print_range(range3.theirs_start, range3.theirs_end)- }- k++- }- filemerge.free_edit(r)- } else {- stdio.print("\t\t", {})- }- stdio.print("\n", {})- } else {- stdio.print(- "{s}: {s} conflict",- {str.view(it.path.ptr, it.path.len as i64), kind_label(c)}- )- val rr2 = ranges_of(st.handles, git.repo, git.open, c, adjacent)- if rr2 is some r2 {- if @len(r2.ranges) > 0 {- stdio.print(" (", {})- val i2: mut usize = 0- for i2 < @len(r2.ranges) {- val x4 = @get(r2.ranges, i2)- if x4 is some range4 {- if i2 > 0 {- stdio.print(", ", {})- }- stdio.print("base ", {})- print_range(range4.base_start, range4.base_end)- stdio.print(", ours ", {})- print_range(range4.ours_start, range4.ours_end)- stdio.print(", theirs ", {})- print_range(range4.theirs_start, range4.theirs_end)- }- i2++- }- stdio.print(")", {})- }- filemerge.free_edit(r2)- }- stdio.print("\n", {})- }- conflict.free_conflict(c)- first = false- }- }- if first {- msg.info_prefix()- stdio.print("no conflicts\n", {})- }- close_git(git)- free_items(items)- view.free_view(v)- store.close(st)- return 0-}--fn normalize(- repo: layout.Repo,- arg: bytes.Bytes-) option[bytes.Bytes] = trust {- val cwd_opt = pathspec.cwd_relative(repo.root)- val cwd: mut bytes.Bytes = bytes.empty()- if cwd_opt is some c {- cwd = c- }- val norm = pathspec.normalize(repo.root, cwd, arg)- if cwd_opt is some c2 {- files.free_buffer(c2)- }- return norm-}--fn delete_sidecar(repo: layout.Repo, base_path: bytes.Bytes, suffix: bytes.Bytes) void = trust {- val full: mut buf.Buf = buf.new(base_path.len + suffix.len + 1)- buf.Buf.put_bytes(full, base_path)- buf.Buf.put_bytes(full, suffix)- val rel: bytes.Bytes = buf.Buf.view(full)- val abs: str.StringView = files.join3(- layout.root_view(repo),- str.from_cstr(c""),- files.to_view(rel)- )- val _ = files.delete(abs)- files.free_path(abs)- buf.Buf.free(full)-}--fn delete_sidecars(repo: layout.Repo, path: bytes.Bytes) void = trust {- delete_sidecar(repo, path, bytes.bytes(c".base", 5))- delete_sidecar(repo, path, bytes.bytes(c".ours", 5))- delete_sidecar(repo, path, bytes.bytes(c".theirs", 7))- val n: mut usize = 2- for n <= 64 {- val suffix: ref u8 = @fmtalloc(".base{d}", {n})- delete_sidecar(repo, path, bytes.from_cstr(suffix))- val sp: mut ref void = suffix as ref void- @free(sp)- val suffix2: ref u8 = @fmtalloc(".theirs{d}", {n})- delete_sidecar(repo, path, bytes.from_cstr(suffix2))- val sp2: mut ref void = suffix2 as ref void- @free(sp2)- n++- }-}--fn read_file(repo: layout.Repo, path: bytes.Bytes) option[bytes.Bytes] = trust {- val abs: str.StringView = files.join3(- layout.root_view(repo),- str.from_cstr(c""),- files.to_view(path)- )- val out = files.read_all(abs)- files.free_path(abs)- return out-}--fn add_blob(tx: mut ref txnmod.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 _ = txnmod.add_known(tx, orf.type_byte, oid, orf.body)- orf.body = bytes.empty()- }- ri++- }- blob.free_build(built)- return id-}--fn replace_placeholder(- out: mut buf.Buf,- cmd: bytes.Bytes,- key: bytes.Bytes,- value: bytes.Bytes-) void = trust {- val i: mut usize = 0- for i < cmd.len {- if i + key.len <= cmd.len && bytes.Bytes.starts_with(- bytes.Bytes.slice(cmd, i, cmd.len),- key- ) {- buf.Buf.put_u8(out, 39)- buf.Buf.put_bytes(out, value)- buf.Buf.put_u8(out, 39)- i = i + key.len- } else {- buf.Buf.put_u8(out, bytes.Bytes.at(cmd, i))- i++- }- }-}--fn run_tool(- repo: layout.Repo,- cmd: bytes.Bytes,- path: bytes.Bytes-) bool = trust {- val abs_base: str.StringView = files.join3(- layout.root_view(repo),- str.from_cstr(c""),- files.to_view(path)- )- val abs_base_b: bytes.Bytes = bytes.bytes(abs_base.ptr, abs_base.len as usize)- val base: mut buf.Buf = buf.new(64)- val ours: mut buf.Buf = buf.new(64)- val theirs: mut buf.Buf = buf.new(64)- buf.Buf.put_bytes(base, abs_base_b)- buf.Buf.put_bytes(base, bytes.bytes(c".base", 5))- buf.Buf.put_bytes(ours, abs_base_b)- buf.Buf.put_bytes(ours, bytes.bytes(c".ours", 5))- buf.Buf.put_bytes(theirs, abs_base_b)- buf.Buf.put_bytes(theirs, bytes.bytes(c".theirs", 7))- val expanded: mut buf.Buf = buf.new(cmd.len + 128)- // Four passes are enough because placeholders do not nest.- replace_placeholder(expanded, cmd, bytes.bytes(c"$BASE", 5), buf.Buf.view(base))- val pass2: mut buf.Buf = buf.new(expanded.len + 128)- replace_placeholder(pass2, buf.Buf.view(expanded), bytes.bytes(c"$OURS", 5), buf.Buf.view(ours))- val pass3: mut buf.Buf = buf.new(pass2.len + 128)- replace_placeholder(- pass3,- buf.Buf.view(pass2),- bytes.bytes(c"$THEIRS", 7),- buf.Buf.view(theirs)- )- val pass4: mut buf.Buf = buf.new(pass3.len + 128)- replace_placeholder(- pass4,- buf.Buf.view(pass3),- bytes.bytes(c"$OUTPUT", 7),- abs_base_b- )- val cstr: ref u8 = bytes.Bytes.to_cstr(buf.Buf.view(pass4))- val rc: i32 = system(cstr)- val cp: mut ref void = cstr as ref void- @free(cp)- buf.Buf.free(base)- buf.Buf.free(ours)- buf.Buf.free(theirs)- buf.Buf.free(expanded)- buf.Buf.free(pass2)- buf.Buf.free(pass3)- buf.Buf.free(pass4)- files.free_path(abs_base)- return rc == 0-}--fn choose(- c: ref conflict.Conflict,- take: bytes.Bytes-) option[ref conflict.ConflictValue] = trust {- if bytes.Bytes.eql(take, bytes.bytes(c"ours", 4)) && @len(c.adds) > 0 {- val o = @get(c.adds, 0)- if o is some v {- return some v- }- }- if bytes.Bytes.eql(take, bytes.bytes(c"theirs", 6)) && @len(c.adds) > 1 {- val o = @get(c.adds, 1)- if o is some v {- return some v- }- }- if bytes.Bytes.eql(take, bytes.bytes(c"base", 4)) && @len(c.removes) > 0 {- val o = @get(c.removes, 0)- if o is some v {- return some v- }- }- return none-}--pub fn resolve(- repo: layout.Repo,- take: bytes.Bytes,- tool: bytes.Bytes,- paths: list[bytes.Bytes]-) i32 = trust {- val snap: i32 = snapshot.run(repo)- if snap != 0 {- return snap- }- val tx_opt = txnmod.begin(repo)- val tx: mut ref txnmod.Txn = none- if tx_opt is some t {- tx = t- } else {- 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()- if wc_opt is some id {- wc = id- }- if objid.Id.is_none(wc) {- msg.error_prefix()- stdio.eprint("no working-copy commit\n", {})- store.close(st)- txnmod.abort(tx)- return 1- }- 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)- txnmod.abort(tx)- return 1- }- val lc: mut ref graph.LoadedCommit = none- if lc_opt is some l {- lc = l- }- val old_root: objid.Id = copy_id(lc.c.root_tree)- val mut_root: mut objid.Id = copy_id(lc.c.root_tree)- val resolved_any: mut bool = false- val i: mut usize = 0- for i < @len(paths) {- val arg = @get(paths, i)- val path: mut bytes.Bytes = bytes.empty()- if arg is some a {- val norm = normalize(repo, a)- if norm is some n {- path = n- }- }- if path.len == 0 {- msg.error_prefix()- stdio.eprint("invalid path\n", {})- continue- }- val flat: list[ref treewalk.FlatEntry] = treewalk.flatten(st.handles, mut_root)- val entry = treewalk.lookup(flat, path)- if entry is none {- msg.error_prefix()- stdio.eprint(- "not a conflicted path: {s}\n",- {str.view(path.ptr, path.len as i64)}- )- treewalk.free_flat(flat)- files.free_buffer(path)- i++- continue- }- val e: mut ref treewalk.FlatEntry = none- if entry is some ee {- e = ee- }- if e.kind != tree.KIND_CONFLICT {- msg.error_prefix()- stdio.eprint(- "not a conflicted path: {s}\n",- {str.view(path.ptr, path.len as i64)}- )- treewalk.free_flat(flat)- files.free_buffer(path)- i++- continue- }- val c_opt = load_conflict(st.handles, e.target)- if c_opt is none {- treewalk.free_flat(flat)- files.free_buffer(path)- i++- continue- }- val c: mut ref conflict.Conflict = none- if c_opt is some cc {- c = cc- }- val present: mut bool = false- val new_kind: mut u8 = tree.KIND_FILE- val new_target: mut objid.Id = objid.id_none()- val took = choose(c, take)- if took is some v {- if v.kind != 0 {- present = true- new_kind = v.kind- new_target = copy_id(v.target)- }- } elif tool.len > 0 {- val tool_ok: bool = run_tool(repo, tool, path)- if tool_ok {- val data_opt = read_file(repo, path)- if data_opt is some data {- new_target = add_blob(tx, data.ptr, data.len)- present = true- new_kind = tree.KIND_FILE- files.free_buffer(data)- }- }- } else {- val data_opt2 = read_file(repo, path)- if data_opt2 is some data2 {- new_target = add_blob(tx, data2.ptr, data2.len)- present = true- new_kind = tree.KIND_FILE- files.free_buffer(data2)- }- }- if present {- val info_opt = stat.read(- files.join3(- layout.root_view(repo),- str.from_cstr(c""),- files.to_view(path)- )- )- if info_opt is some info {- if info.executable {- new_kind = tree.KIND_EXECUTABLE- }- }- // Remember the resolution when it is a plain file.- if new_kind == tree.KIND_FILE || new_kind == tree.KIND_EXECUTABLE {- val body_opt = state.read_body(st.handles, e.target, types.CONFLICT)- if body_opt is some body {- val _ = resolutions.record(repo, body, new_target)- files.free_buffer(body)- }- }- }- val replaced = treeedit.replace(- tx,- st.handles,- mut_root,- path,- present,- new_kind,- new_target- )- if replaced is some nr {- free_id(mut_root)- mut_root = copy_id(nr)- free_id(nr)- resolved_any = true- }- free_id(new_target)- conflict.free_conflict(c)- treewalk.free_flat(flat)- files.free_buffer(path)- i++- }- val status: mut i32 = 1- if resolved_any {- val sig: prim.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 nc: mut ref commit.Commit = @alloc(@sizeof(commit.Commit)) as ref commit.Commit- nc.version = 1- nc.parents = parents- nc.root_tree = copy_id(mut_root)- nc.change_id = lc.c.change_id- nc.author = lc.c.author- nc.committer = sig- nc.message = lc.c.message- nc.renames_state = lc.c.renames_state- nc.renames = lc.c.renames- nc.extra = lc.c.extra- val body: bytes.Bytes = commit.encode(nc)- val new_id: objid.Id = txnmod.add_object(tx, types.COMMIT, body)- viewops.remove_head(tx.view, wc)- viewops.move_bookmarks(tx.view, wc, new_id)- viewops.set_workspace(tx.view, new_id)- viewops.rebuild_heads(tx.view)- status = txnmod.finish(tx, bytes.bytes(c"resolve", 7))- if status == 0 {- val st2: store.Store = store.open_all(repo)- val ms: i32 = checkout.materialize_commit(- repo,- st2.handles,- some old_root,- mut_root- )- store.close(st2)- if ms != 0 {- status = ms- }- val j: mut usize = 0- for j < @len(paths) {- val arg2 = @get(paths, j)- if arg2 is some a2 {- val norm2 = normalize(repo, a2)- if norm2 is some n2 {- delete_sidecars(repo, n2)- files.free_buffer(n2)- }- }- j++- }- }- val nrp: mut ref void = nc.root_tree.ptr as ref void- @free(nrp)- @listfree(parents)- @free(nc as ref void)- identity.free_sig(sig)- free_id(new_id)- } else {- txnmod.abort(tx)- }- free_id(old_root)- free_id(mut_root)- free_id(wc)- graph.free_loaded(lc)- store.close(st)- return status-}--- a/veins/src/cli/rm_cmd.sx+++ /dev/null@@ -1,661 +0,0 @@-/// `vn rm [-delete] <path>...`: remove paths from the working-copy tree while-/// keeping the files on disk by default.-///-/// Arguments are repository paths or globs resolved against the current-/// directory. Supported wildcards are `*`, `?`, and `**`; `*` and `?` do not-/// cross directory separators. Untracking a file that is not covered by-/// `.vnexclude` or `.gitignore` only lasts until the next snapshot, so `rm`-/// warns in that case.--val str = use("std/string")-val stdio = use("std/stdio")-val msg = use("../core/msg.sx")-val fs = use("std/fs")-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 names = use("../object/names.sx")-val commit = use("../object/commit.sx")-val graph = use("../object/graph.sx")-val tree = use("../object/tree.sx")-val treewalk = use("../object/treewalk.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 ignore = use("../worktree/ignore.sx")-val pathspec = use("../worktree/pathspec.sx")-val files = use("../io/files.sx")--fn cmd_is(a: ref u8, text: ref u8, len: usize) bool = trust {- 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 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 free_id(id: objid.Id) void = trust {- if id.ptr != none {- val p: mut ref void = id.ptr as ref void- @free(p)- }-}--fn free_path_list(xs: list[bytes.Bytes]) void = trust {- for p in xs {- if p.ptr != none {- val pp: mut ref void = p.ptr as ref void- @free(pp)- }- }- @listfree(xs)-}--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_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_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 starts_with_child(path: bytes.Bytes, parent: bytes.Bytes) bool = trust {- if path.len <= parent.len || !bytes.Bytes.starts_with(path, parent) {- return false- }- return bytes.Bytes.at(path, parent.len) == 47-}--fn literal_matches(operand: bytes.Bytes, path: bytes.Bytes) bool = trust {- if bytes.Bytes.eql(path, operand) {- return true- }- return starts_with_child(path, operand)-}--fn glob_matches(operand: bytes.Bytes, path: bytes.Bytes) bool = trust {- if ignore.glob_match(operand, path) {- return true- }- val i: mut usize = 0- for i < path.len {- if bytes.Bytes.at(path, i) == 47 {- if ignore.glob_match(operand, bytes.Bytes.slice(path, 0, i)) {- return true- }- }- i++- }- return false-}--fn operand_matches(operand: bytes.Bytes, path: bytes.Bytes) bool = trust {- if pathspec.has_glob(operand) {- return glob_matches(operand, path)- }- return literal_matches(operand, path)-}--fn contains_path(xs: list[bytes.Bytes], path: bytes.Bytes) bool = trust {- for p in xs {- if bytes.Bytes.eql(p, path) {- return true- }- }- return false-}--fn append_unique(xs: mut list[bytes.Bytes], path: bytes.Bytes) void = trust {- if !contains_path(xs, path) {- @append(xs, bytes.Bytes.dup(path))- }-}--fn match_operands(- handles: list[ref store.Handle],- root_tree: objid.Id,- operands: list[bytes.Bytes],- matched: mut list[bool]-) list[bytes.Bytes] = trust {- val removes: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()- val entries: list[ref treewalk.FlatEntry] = treewalk.flatten(handles, root_tree)- for e in entries {- val i: mut usize = 0- for i < @len(operands) {- val o = @get(operands, i)- if o is some operand {- if operand_matches(operand, e.path) {- @set(matched, i, true)- append_unique(removes, e.path)- }- }- i++- }- }- treewalk.free_flat(entries)- return removes-}--fn subtree_affected(prefix: bytes.Bytes, removes: list[bytes.Bytes]) bool = trust {- if prefix.len == 0 {- return @len(removes) > 0- }- for r in removes {- if bytes.Bytes.eql(prefix, r) {- return true- }- if starts_with_child(r, prefix) || starts_with_child(prefix, r) {- return true- }- }- return false-}--fn path_removed(path: bytes.Bytes, removes: list[bytes.Bytes]) bool = trust {- for r in removes {- if bytes.Bytes.eql(path, r) || starts_with_child(path, r) {- return true- }- }- return false-}--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 result: mut objid.Id = objid.id_none()- match encoded {- ok body => {- result = txn.add_object(tx, types.TREE, body)- }- err _ => {- }- }- @listfree(t.entries)- return result-}--fn filter_tree(- tx: mut ref txn.Txn,- handles: list[ref store.Handle],- tree_id: objid.Id,- prefix: bytes.Bytes,- removes: list[bytes.Bytes],- depth: usize-) option[objid.Id] = trust {- if depth > 4096 {- return some(copy_id(tree_id))- }- if !subtree_affected(prefix, removes) {- return some(copy_id(tree_id))- }- val t_opt = treewalk.read_tree(handles, tree_id)- val t: mut ref tree.Tree = none- match t_opt {- some x => {- t = x- }- none => {- return some(copy_id(tree_id))- }- }- val entries: mut list[ref tree.TreeEntry] = lists.new[ref tree.TreeEntry]()- for e in t.entries {- val full: bytes.Bytes = join_path(prefix, e.name)- if path_removed(full, removes) {- files.free_buffer(full)- continue- }- if e.kind == tree.KIND_SUBTREE && subtree_affected(full, removes) {- val child = filter_tree(tx, handles, e.target, full, removes, depth + 1)- if child is some cid {- @append(entries, tree.entry(bytes.Bytes.dup(e.name), e.kind, cid))- }- } else {- @append(entries, tree.entry(bytes.Bytes.dup(e.name), e.kind, copy_id(e.target)))- }- files.free_buffer(full)- }- tree.free_tree(t)-- val result: mut option[objid.Id] = none- if @len(entries) > 0 {- val encoded = tree.encode(entries)- match encoded {- ok body => {- result = some(txn.add_object(tx, types.TREE, body))- }- err _ => {- }- }- }- for e in entries {- if e.name.ptr != none {- val np: mut ref void = e.name.ptr as ref void- @free(np)- }- free_id(e.target)- val ep: mut ref void = e as ref void- @free(ep)- }- @listfree(entries)- return result-}--fn delete_one(repo: layout.Repo, rel: bytes.Bytes) bool = trust {- val path_view: str.StringView = str.view(rel.ptr, rel.len as i64)- val final: str.StringView = files.join(layout.root_view(repo), path_view)- val removed: bool = files.delete(final)- files.free_path(final)- return removed-}--fn prune_empty_parents(repo: layout.Repo, rel: bytes.Bytes) void = trust {- val i: mut usize = rel.len- for i > 0 {- val slash: mut i64 = -1- val k: mut usize = 0- for k < i {- if bytes.Bytes.at(rel, k) == 47 {- slash = k as i64- }- k++- }- if slash < 0 {- break- }- val parent: bytes.Bytes = bytes.Bytes.slice(rel, 0, slash as usize)- val path_view: str.StringView = str.view(parent.ptr, parent.len as i64)- val abs: str.StringView = files.join(layout.root_view(repo), path_view)- val removed: bool = fs.rmdir_path(abs)- files.free_path(abs)- if !removed {- break- }- i = slash as usize- }-}--fn delete_paths(repo: layout.Repo, removes: list[bytes.Bytes]) i32 = trust {- val failed: mut usize = 0- for rel in removes {- if !delete_one(repo, rel) {- failed++- } else {- prune_empty_parents(repo, rel)- }- }- if failed > 0 {- msg.warning_prefix()- stdio.eprint("could not delete {d} path(s) from disk\n", {failed})- return 1- }- return 0-}--fn run_removal(repo: layout.Repo, operands: list[bytes.Bytes], delete_mode: bool) 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- }- 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)- val lc: mut ref graph.LoadedCommit = none- match lc_opt {- some x => {- lc = x- }- none => {- msg.error_prefix()- stdio.eprint("cannot read working-copy commit\n", {})- store.close(st)- txn.abort(tx)- free_id(wc)- return 1- }- }-- val matched: mut list[bool] = lists.new[bool]()- val i: mut usize = 0- for i < @len(operands) {- @append(matched, false)- i++- }- val removes: list[bytes.Bytes] = match_operands(- st.handles,- lc.c.root_tree,- operands,- matched- )- val unmatched: mut bool = false- val j: mut usize = 0- for j < @len(operands) {- val o = @get(operands, j)- if o is some operand {- val m = @get(matched, j)- val is_matched: mut bool = false- if m is some flag {- is_matched = flag- }- if !is_matched {- msg.error_prefix()- stdio.eprint(- "path is not tracked: {s}\n",- {str.view(operand.ptr, operand.len as i64)}- )- unmatched = true- }- }- j++- }- if unmatched {- free_path_list(removes)- @listfree(matched)- graph.free_loaded(lc)- free_id(wc)- store.close(st)- txn.abort(tx)- return 1- }-- if !delete_mode {- for rel in removes {- if !ignore.path_ignored(layout.root_view(repo), rel) {- msg.warning_prefix()- stdio.eprint(- "{s} is not ignored and will be re-added on the next snapshot\n",- {str.view(rel.ptr, rel.len as i64)}- )- }- }- }-- val new_root_opt = filter_tree(tx, st.handles, lc.c.root_tree, bytes.empty(), removes, 0)- val new_root: mut objid.Id = objid.id_none()- if new_root_opt is some id {- new_root = id- } else {- new_root = empty_tree_id(tx)- }- if objid.Id.is_none(new_root) || objid.Id.eql(new_root, lc.c.root_tree) {- msg.error_prefix()- stdio.eprint("no tracked paths to remove\n", {})- free_id(new_root)- free_path_list(removes)- @listfree(matched)- graph.free_loaded(lc)- free_id(wc)- store.close(st)- txn.abort(tx)- return 1- }-- 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] = lists.new[ref commit.Rename]()- 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 = new_root- nc.change_id = lc.c.change_id- nc.author = lc.c.author- nc.committer = sig- nc.message = lc.c.message- 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)- viewops.remove_head(tx.view, wc)- viewops.move_bookmarks(tx.view, wc, new_id)- viewops.set_workspace(tx.view, new_id)- viewops.rebuild_heads(tx.view)- val status: mut i32 = txn.finish(tx, bytes.bytes(c"rm", 2))- if status == 0 {- val _ = gitmap.mark_native(repo, new_id)- }-- @listfree(parents)- @listfree(renames)- free_kvs(extra)- @free(nc as ref void)- free_id(new_id)- free_id(new_root)- identity.free_sig(sig)- graph.free_loaded(lc)- free_id(wc)- store.close(st)-- if status == 0 {- if delete_mode {- val del: i32 = delete_paths(repo, removes)- if del != 0 {- status = del- }- }- msg.info_prefix()- stdio.print("untracked {d} path(s)\n", {@len(removes)})- }- free_path_list(removes)- @listfree(matched)- return status-}--pub fn run(args: list[ref u8], start: usize) i32 = trust {- val delete_mode: mut bool = false- val operands: mut list[ref u8] = lists.new[ref u8]()- 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"-delete", 7) {- delete_mode = true- } elif !end_flags && is_flag(a) {- msg.error_prefix()- stdio.eprint("unknown flag: {s}\n", {str.from_cstr(a)})- @listfree(operands)- return 1- } else {- @append(operands, a)- }- }- i++- }- if @len(operands) == 0 {- msg.error_prefix()- stdio.eprint("rm requires at least one path\n", {})- @listfree(operands)- return 1- }-- val repo_opt = layout.discover(str.from_cstr(c"."))- 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\n", {})- @listfree(operands)- return 1- }- }-- val snap: i32 = snapshot.run(repo)- if snap != 0 {- @listfree(operands)- layout.free_repo(repo)- return snap- }-- val cwd_opt = pathspec.cwd_relative(repo.root)- val cwd_rel: mut bytes.Bytes = bytes.empty()- match cwd_opt {- some c => {- cwd_rel = c- }- none => {- msg.error_prefix()- stdio.eprint("cannot determine current directory\n", {})- @listfree(operands)- layout.free_repo(repo)- return 1- }- }-- val normalized: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()- val bad: mut bool = false- for a in operands {- val arg: bytes.Bytes = bytes.from_cstr(a)- val norm_opt = pathspec.normalize(repo.root, cwd_rel, arg)- val norm: mut bytes.Bytes = bytes.empty()- match norm_opt {- some n => {- norm = n- }- none => {- msg.error_prefix()- stdio.eprint(- "path is outside the repository: {s}\n",- {str.view(arg.ptr, arg.len as i64)}- )- bad = true- }- }- if bad {- if norm.ptr != none {- val np: mut ref void = norm.ptr as ref void- @free(np)- }- break- }- if norm.len == 0 || !names.valid_path(norm) {- msg.error_prefix()- stdio.eprint(- "invalid path: {s}\n",- {str.view(arg.ptr, arg.len as i64)}- )- if norm.ptr != none {- val np2: mut ref void = norm.ptr as ref void- @free(np2)- }- bad = true- break- }- @append(normalized, norm)- }- if bad {- if cwd_rel.ptr != none {- val cp: mut ref void = cwd_rel.ptr as ref void- @free(cp)- }- free_path_list(normalized)- @listfree(operands)- layout.free_repo(repo)- return 1- }- if @len(normalized) == 0 {- msg.error_prefix()- stdio.eprint("rm requires at least one path\n", {})- if cwd_rel.ptr != none {- val cp2: mut ref void = cwd_rel.ptr as ref void- @free(cp2)- }- @listfree(normalized)- @listfree(operands)- layout.free_repo(repo)- return 1- }-- val status: i32 = run_removal(repo, normalized, delete_mode)- if cwd_rel.ptr != none {- val cp3: mut ref void = cwd_rel.ptr as ref void- @free(cp3)- }- free_path_list(normalized)- @listfree(operands)- layout.free_repo(repo)- return status-}--- a/veins/src/cli/selftest_cmd.sx+++ /dev/null@@ -1,647 +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")-val algebra = use("../merge/algebra.sx")-val filemerge = use("../merge/filemerge.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 mkid(seed: u8) objid.Id = trust {- val p: ref u8 = @alloc(32) as ref u8- val i: mut usize = 0- for i < 32 {- @store8(@ptradd(p, i as i64), (seed + i) as u8)- i++- }- return objid.id(p)-}--fn test_algebra() void = trust {- val handles: list[ref store.Handle] = lists.new[ref store.Handle]()- val a: objid.Id = mkid(1)- val b: objid.Id = mkid(2)- val c: objid.Id = mkid(3)-- val adds: mut list[ref conflict.ConflictValue] = lists.new[ref conflict.ConflictValue]()- val rems: mut list[ref conflict.ConflictValue] = lists.new[ref conflict.ConflictValue]()- @append(adds, conflict.value(tree.KIND_FILE, a))- @append(adds, conflict.value(tree.KIND_FILE, b))- @append(rems, conflict.value(tree.KIND_FILE, a))- val s1: algebra.Sum = algebra.simplify(handles, adds, rems)- assert @len(s1.adds) == 1- assert @len(s1.removes) == 0- algebra.free_sum(s1)-- val adds2: mut list[ref conflict.ConflictValue] = lists.new[ref conflict.ConflictValue]()- val rems2: mut list[ref conflict.ConflictValue] = lists.new[ref conflict.ConflictValue]()- @append(adds2, conflict.value(tree.KIND_FILE, a))- @append(adds2, conflict.value(tree.KIND_FILE, a))- @append(rems2, conflict.value(tree.KIND_FILE, b))- val s2: algebra.Sum = algebra.simplify(handles, adds2, rems2)- val got = algebra.resolved(s2)- if got is some g {- assert objid.Id.eql(g.target, a)- } else {- assert false- }- algebra.free_sum(s2)-- // Repeated cancellation and idempotence on a fixed shape.- val adds3: mut list[ref conflict.ConflictValue] = lists.new[ref conflict.ConflictValue]()- val rems3: mut list[ref conflict.ConflictValue] = lists.new[ref conflict.ConflictValue]()- @append(adds3, conflict.value(tree.KIND_FILE, a))- @append(adds3, conflict.value(tree.KIND_FILE, b))- @append(adds3, conflict.value(tree.KIND_FILE, c))- @append(adds3, conflict.value(tree.KIND_FILE, a))- @append(rems3, conflict.value(tree.KIND_FILE, b))- @append(rems3, conflict.value(tree.KIND_FILE, c))- @append(rems3, conflict.value(tree.KIND_FILE, a))- val sm: algebra.Sum = algebra.simplify(handles, adds3, rems3)- assert @len(sm.adds) == 1- assert @len(sm.removes) == 0- algebra.free_sum(sm)- @listfree(handles)-- val ap: mut ref void = a.ptr as ref void- @free(ap)- val bp: mut ref void = b.ptr as ref void- @free(bp)- val cp: mut ref void = c.ptr as ref void- @free(cp)-}--fn test_file_merge() void = trust {- val base = filemerge.split_lines(bytes.bytes(c"a\nb\nc\n", 6))- val ours = filemerge.split_lines(bytes.bytes(c"A\nb\nc\n", 6))- val theirs = filemerge.split_lines(bytes.bytes(c"a\nb\nC\n", 6))- val r = filemerge.merge_lines(base, ours, theirs, false)- assert !r.conflicted- assert bytes.Bytes.eql(r.data, bytes.bytes(c"A\nb\nC\n", 6))- filemerge.free_edit(r)- @listfree(base)- @listfree(ours)- @listfree(theirs)-- val base2 = filemerge.split_lines(bytes.bytes(c"a\nb\n", 4))- val ours2 = filemerge.split_lines(bytes.bytes(c"A\nb\n", 4))- val theirs2 = filemerge.split_lines(bytes.bytes(c"X\nb\n", 4))- val r2 = filemerge.merge_lines(base2, ours2, theirs2, false)- assert r2.conflicted- assert bytes.Bytes.eql(r2.data, bytes.bytes(c"A\nb\n", 4))- filemerge.free_edit(r2)- @listfree(base2)- @listfree(ours2)- @listfree(theirs2)-}--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,- owned: bytes.empty()- }- 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,- owned: bytes.empty()- }- 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()- test_algebra()- test_file_merge()-- 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/veins/src/cli/serve_cmd.sx+++ /dev/null@@ -1,149 +0,0 @@-/// `vn serve`: native server over stdio or TLS.--val stdio = use("std/stdio")-val str = use("std/string")-val bytes = use("../core/bytes.sx")-val layout = use("../store/layout.sx")-val server = use("../server/serve.sx")-val cmsg = use("../core/msg.sx")--fn parse_u64(text: bytes.Bytes) option[u64] = trust {- if text.len == 0 {- return none- }- val value: 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- }- value = value * 10 + (c - 48) as u64- i++- }- return some value-}--pub fn run(args: list[ref u8], start: usize) i32 = trust {- val stdio_mode: mut bool = false- val listen: mut bytes.Bytes = bytes.empty()- val root: mut str.StringView = str.from_cstr(c".")- val cert: mut bytes.Bytes = bytes.empty()- val key: mut bytes.Bytes = bytes.empty()- val repo_path: mut str.StringView = str.from_cstr(c".")- val quota_bytes: mut u64 = 0- 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)- if bytes.Bytes.eql(av, bytes.bytes(c"-stdio", 6)) {- stdio_mode = true- if i + 1 < @len(args) {- val v = @get(args, i + 1)- if v is some r {- repo_path = str.from_cstr(r)- i++- }- }- } elif bytes.Bytes.eql(av, bytes.bytes(c"-listen", 7)) {- if i + 1 < @len(args) {- val v = @get(args, i + 1)- if v is some r {- listen = bytes.Bytes.dup(bytes.from_cstr(r))- i++- }- }- } elif bytes.Bytes.eql(av, bytes.bytes(c"-root", 5)) {- if i + 1 < @len(args) {- val v = @get(args, i + 1)- if v is some r {- root = str.from_cstr(r)- i++- }- }- } elif bytes.Bytes.eql(av, bytes.bytes(c"-tls-cert", 9)) {- if i + 1 < @len(args) {- val v = @get(args, i + 1)- if v is some r {- cert = bytes.Bytes.dup(bytes.from_cstr(r))- i++- }- }- } elif bytes.Bytes.eql(av, bytes.bytes(c"-tls-key", 8)) {- if i + 1 < @len(args) {- val v = @get(args, i + 1)- if v is some r {- key = bytes.Bytes.dup(bytes.from_cstr(r))- i++- }- }- } elif bytes.Bytes.eql(av, bytes.bytes(c"-quota", 6)) {- val v = @get(args, i + 1)- if v is some r {- val parsed = parse_u64(bytes.from_cstr(r))- if parsed is none {- cmsg.error_prefix()- stdio.eprint("-quota requires a byte count\n", {})- return 1- }- match parsed {- some n => {- quota_bytes = n- }- none => {- return 1- }- }- i++- } else {- cmsg.error_prefix()- stdio.eprint("-quota requires a byte count\n", {})- return 1- }- } else {- cmsg.error_prefix()- stdio.eprint("unknown serve option: {s}\n", {str.from_cstr(a)})- return 1- }- }- i++- }- if stdio_mode {- val repo_opt = layout.discover(repo_path)- if repo_opt is none {- cmsg.error_prefix()- stdio.eprint("not a veins repository\n", {})- return 1- }- val repo: mut layout.Repo = layout.Repo{root: bytes.empty()}- match repo_opt {- some r => {- repo = r- }- none => {- return 1- }- }- return server.serve_stdio(repo, quota_bytes)- }- if listen.ptr == none {- cmsg.error_prefix()- stdio.eprint("serve requires -stdio or -listen\n", {})- return 1- }- if cert.ptr == none || key.ptr == none {- cmsg.error_prefix()- stdio.eprint("TLS requires -tls-cert and -tls-key\n", {})- return 1- }- val root_repo: layout.Repo = layout.Repo{- root: bytes.Bytes.dup(bytes.bytes(root.ptr, root.len))- }- val code: i32 = server.serve_listen(listen, root_repo, cert, key, quota_bytes)- layout.free_repo(root_repo)- bytes.free_owned(listen)- bytes.free_owned(cert)- bytes.free_owned(key)- return code-}--- a/veins/src/cli/show_cmd.sx+++ /dev/null@@ -1,206 +0,0 @@-/// `vn show <rev>`: display a commit and its diff against its first parent.--val str = use("std/string")-val stdio = use("std/stdio")-val msg = use("../core/msg.sx")-val bytes = use("../core/bytes.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 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")-val diff = use("diff_cmd.sx")--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_id(id: objid.Id) void = trust {- if id.ptr != none {- val p: mut ref void = id.ptr as ref void- @free(p)- }-}--fn dup_z(b: bytes.Bytes) bytes.Bytes = trust {- val out: ref u8 = @alloc(b.len + 1) as ref u8- if b.len > 0 {- @memcpy(out as ref void, b.ptr as ref void, b.len)- }- @store8(@ptradd(out, b.len as i64), 0)- return bytes.bytes(out, b.len)-}--fn print_short(id: objid.Id) void = trust {- val hex: ref u8 = objid.Id.hex(id)- stdio.print("{s}", {str.view(hex, 12)})- @free(hex as ref void)-}--fn 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(copy_id(parent.c.root_tree))- graph.free_loaded(parent)- }- }- }- graph.free_loaded(lc)- }- return out-}--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 resolved = graph.resolve(st.handles, v, rev)- val target: mut objid.Id = objid.id_none()- val have_target: mut bool = false- if resolved is some id {- target = copy_id(id)- have_target = true- }- if !have_target {- msg.error_prefix()- if rev.len == 0 {- stdio.eprint("no working-copy commit\n", {})- } else {- stdio.eprint("unknown revision: {s}\n", {str.view(rev.ptr, rev.len as i64)})- }- view.free_view(v)- store.close(st)- return 1- }-- val lc_opt = graph.load_commit(st.handles, target)- val lc: mut ref graph.LoadedCommit = none- match lc_opt {- some x => {- lc = x- }- none => {- msg.error_prefix()- stdio.eprint("cannot read commit\n", {})- view.free_view(v)- store.close(st)- free_id(target)- return 1- }- }-- val hex: ref u8 = objid.Id.hex(target)- val cid_raw: bytes.Bytes = changeid.encode(lc.c.change_id)- val cid: bytes.Bytes = dup_z(cid_raw)- changeid.free(cid_raw)- val stamp_raw: bytes.Bytes = datetime.format_utc(lc.c.committer.seconds)- val stamp: bytes.Bytes = dup_z(stamp_raw)- val author_name: bytes.Bytes = dup_z(lc.c.author.name)- val author_email: bytes.Bytes = dup_z(lc.c.author.email)- if col_titles {- stdio.print("commit {s}\n", {str.view(hex, 64)})- stdio.print("change {s}\n", {str.view(cid.ptr, cid.len as i64)})- stdio.print("author {s} <{s}>\n", {- str.view(author_name.ptr, author_name.len as i64),- str.view(author_email.ptr, author_email.len as i64)- })- stdio.print("date {s}\n", {str.view(stamp.ptr, stamp.len as i64)})- stdio.print("parents ", {})- if @len(lc.c.parents) == 0 {- stdio.print("<none>", {})- } else {- val pi: mut usize = 0- for pi < @len(lc.c.parents) {- if pi > 0 {- stdio.print(" ", {})- }- val p = @get(lc.c.parents, pi)- if p is some pid {- print_short(pid)- }- pi++- }- }- stdio.print("\n", {})- val names = viewops.bookmark_names(v, target)- if @len(names) > 0 {- stdio.print("bookmarks", {})- for name in names {- val nz: bytes.Bytes = dup_z(name)- stdio.print(" [{s}]", {str.view(nz.ptr, nz.len as i64)})- val nzp: mut ref void = nz.ptr as ref void- @free(nzp)- }- stdio.print("\n", {})- }- @listfree(names)- stdio.print("\n", {})- if lc.c.message.len > 0 {- val msgz: bytes.Bytes = dup_z(lc.c.message)- stdio.print("{s}\n", {str.view(msgz.ptr, msgz.len as i64)})- val msgzp: mut ref void = msgz.ptr as ref void- @free(msgzp)- } else {- stdio.print("<unset>\n", {})- }- stdio.print("\n", {})- }-- val old_tree: option[objid.Id] = parent_tree(st.handles, target)- val new_tree: option[objid.Id] = some(copy_id(lc.c.root_tree))- val git: mut diff.GitSource = diff.open_git(repo)- val _ = diff.render(st.handles, git, old_tree, new_tree)- diff.close_git(git)-- if old_tree is some ot {- free_id(ot)- }- if new_tree is some nt {- free_id(nt)- }- @free(hex as ref void)- val cidp: mut ref void = cid.ptr as ref void- @free(cidp)- val stampp: mut ref void = stamp.ptr as ref void- @free(stampp)- val anp: mut ref void = author_name.ptr as ref void- @free(anp)- val aep: mut ref void = author_email.ptr as ref void- @free(aep)- graph.free_loaded(lc)- view.free_view(v)- store.close(st)- free_id(target)- return 0-}--- a/veins/src/cli/status_cmd.sx+++ /dev/null@@ -1,149 +0,0 @@-/// `vn stat` (alias `vn status`): show working-copy changes relative to the-/// parent commit.--val stdio = use("std/stdio")-val msg = use("../core/msg.sx")-val terminal = use("std/terminal")-val str = use("std/string")-val lists = use("../core/lists.sx")-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 {- terminal.print(str.from_cstr(c"A"), terminal.Color.BrightGreen)- stdio.print(" {s}\n", {path_view})- } elif c.new_kind == treewalk.KIND_MISSING {- terminal.print(str.from_cstr(c"D"), terminal.Color.Red)- stdio.print(" {s}\n", {path_view})- } elif c.new_kind == tree.KIND_CONFLICT {- terminal.print(str.from_cstr(c"C"), terminal.Color.BrightRed)- stdio.print(" {s}\n", {path_view})- conflicted_count++- } else {- terminal.print(str.from_cstr(c"M"), terminal.Color.Cyan)- stdio.print(" {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})- }- val start: mut list[objid.Id] = lists.new[objid.Id]()- @append(start, graph.copy_id(wc))- val ancestry: list[objid.Id] = graph.collect(st.handles, start)- val conflicted_commits: mut usize = 0- for cid in ancestry {- val lc_opt = graph.load_commit(st.handles, cid)- if lc_opt is some lc {- if treewalk.conflicted(st.handles, lc.c.root_tree) {- conflicted_commits++- }- graph.free_loaded(lc)- }- }- if conflicted_commits > 0 {- stdio.print("{d} conflicted commit(s) in ancestry\n", {conflicted_commits})- }- graph.free_ids(ancestry)- @listfree(start)- 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/veins/src/cli/tag_cmd.sx+++ /dev/null@@ -1,680 +0,0 @@-/// `vn tag`: manage named pointers to commits (tags).-///-/// `vn tag set <name>` creates or moves a tag at the working-copy commit,-/// `vn tag ls` lists tags, `vn tag rm <name>` deletes one, and-/// `vn tag latest` prints the name of the newest tag.--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 buf = use("../core/buf.sx")-val prim = use("../core/primitives.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 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 snapshot = use("../worktree/snapshot.sx")--fn cmd_is(a: ref u8, text: ref u8, len: usize) bool = trust {- 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 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 free_id(id: objid.Id) void = trust {- if id.ptr != none {- val p: mut ref void = id.ptr as ref void- @free(p)- }-}--fn dup_z(b: bytes.Bytes) bytes.Bytes = trust {- val out: ref u8 = @alloc(b.len + 1) as ref u8- if b.len > 0 {- @memcpy(out as ref void, b.ptr as ref void, b.len)- }- @store8(@ptradd(out, b.len as i64), 0)- return bytes.bytes(out, b.len)-}--fn contains_seq(name: bytes.Bytes, needle: bytes.Bytes) bool = trust {- if needle.len == 0 || needle.len > name.len {- return false- }- val last: usize = name.len - needle.len- val i: mut usize = 0- for i <= last {- if bytes.Bytes.eql(bytes.Bytes.slice(name, i, i + needle.len), needle) {- return true- }- i++- }- return false-}--/// Tags are exported as git tags, so apply the same ref-name restrictions as-/// bookmarks.-fn valid_tag_name(name: bytes.Bytes) bool = trust {- if name.len == 0 || name.len > prim.MAX_NAME_LEN {- return false- }- val first: u8 = bytes.Bytes.at(name, 0)- if first == 45 || first == 47 || first == 46 {- return false- }- val last: u8 = bytes.Bytes.at(name, name.len - 1)- if last == 47 || last == 46 {- return false- }- val i: mut usize = 0- for i < name.len {- val c: u8 = bytes.Bytes.at(name, i)- if c == 0 || c == 32 || c < 32 || c == 127 {- return false- }- if c == 126 || c == 94 || c == 58 || c == 63 || c == 42 || c == 91 || c == 92 {- return false- }- i++- }- if contains_seq(name, bytes.bytes(c"..", 2)) {- return false- }- if contains_seq(name, bytes.bytes(c"@{", 2)) {- return false- }- if contains_seq(name, bytes.bytes(c"//", 2)) {- return false- }- if bytes.Bytes.eql(name, bytes.bytes(c"@", 1)) {- return false- }- val lock: bytes.Bytes = bytes.bytes(c".lock", 5)- if name.len >= lock.len- && bytes.Bytes.eql(bytes.Bytes.slice(name, name.len - lock.len, name.len), lock) {- return false- }- return true-}--fn make_description(prefix: bytes.Bytes, name: bytes.Bytes) bytes.Bytes = trust {- val b: mut buf.Buf = buf.new(prefix.len + 1 + name.len)- buf.Buf.put_bytes(b, prefix)- buf.Buf.put_u8(b, 32)- buf.Buf.put_bytes(b, name)- val out: bytes.Bytes = bytes.Bytes.dup(buf.Buf.view(b))- buf.Buf.free(b)- return out-}--fn short_commit(id: objid.Id, n: usize) str.StringView = trust {- val hex: ref u8 = objid.Id.hex(id)- val mut_width: mut usize = 12- if n > 0 {- mut_width = n- }- if mut_width > 64 {- mut_width = 64- }- return str.view(hex, mut_width as i64)-}--fn short_change(cid: objid.ChangeId) bytes.Bytes = trust {- val full: bytes.Bytes = changeid.encode(cid)- val width: mut usize = 8- if full.len < width {- width = full.len- }- val out: bytes.Bytes = dup_z(bytes.Bytes.slice(full, 0, width))- changeid.free(full)- return out-}--fn print_cell(text: str.StringView, width: usize) void = trust {- stdio.print("{s}", {text})- val pad: mut i64 = width as i64 - text.len- for pad > 0 {- stdio.print(" ", {})- pad--- }-}--fn find_tag(v: ref view.View, name: bytes.Bytes) option[usize] = 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 some i- }- }- i++- }- return none-}--/// Compare tag names as natural versions: digit runs compare numerically so-/// v0.0.10 sorts after v0.0.9.-fn natural_compare(a: bytes.Bytes, b: bytes.Bytes) i64 = trust {- val i: mut usize = 0- val j: mut usize = 0- for i < a.len && j < b.len {- val ca: u8 = bytes.Bytes.at(a, i)- val cb: u8 = bytes.Bytes.at(b, j)- val da: bool = ca >= 48 && ca <= 57- val db: bool = cb >= 48 && cb <= 57- if da && db {- val si: mut usize = i- val sj: mut usize = j- for si < a.len- && (bytes.Bytes.at(a, si) >= 48 && bytes.Bytes.at(a, si) <= 57) {- si++- }- for sj < b.len- && (bytes.Bytes.at(b, sj) >= 48 && bytes.Bytes.at(b, sj) <= 57) {- sj++- }- val ni: mut usize = i- val nj: mut usize = j- for ni < si && bytes.Bytes.at(a, ni) == 48 {- ni++- }- for nj < sj && bytes.Bytes.at(b, nj) == 48 {- nj++- }- val la: usize = si - ni- val lb: usize = sj - nj- if la != lb {- if la < lb {- return -1- }- return 1- }- val k: mut usize = 0- for k < la {- val xa: u8 = bytes.Bytes.at(a, ni + k)- val xb: u8 = bytes.Bytes.at(b, nj + k)- if xa != xb {- if xa < xb {- return -1- }- return 1- }- k++- }- i = si- j = sj- } else {- if ca != cb {- if ca < cb {- return -1- }- return 1- }- i++- j++- }- }- if i < a.len {- return 1- }- if j < b.len {- return -1- }- return 0-}--fn run_set(repo: layout.Repo, args: list[ref u8], start: usize) i32 = trust {- val name: mut bytes.Bytes = bytes.empty()- val rev: mut bytes.Bytes = bytes.empty()- 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 && is_flag(a) {- msg.error_prefix()- stdio.eprint("unknown flag: {s}\n", {str.from_cstr(a)})- return 1- } else {- if name.len == 0 {- name = bytes.from_cstr(a)- } elif rev.len == 0 {- rev = bytes.from_cstr(a)- } else {- msg.error_prefix()- stdio.eprint("tag set accepts a name and one revision\n", {})- return 1- }- }- }- i++- }- if name.len == 0 {- msg.error_prefix()- stdio.eprint("tag set requires a name\n", {})- return 1- }- if !valid_tag_name(name) {- msg.error_prefix()- stdio.eprint(- "invalid tag name: {s}\n",- {str.view(name.ptr, name.len as i64)}- )- return 1- }-- 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 resolved = graph.resolve(st.handles, tx.view, rev)- val target: mut objid.Id = objid.id_none()- val mut_found: mut bool = false- if resolved is some id {- target = copy_id(id)- mut_found = true- }- if !mut_found {- msg.error_prefix()- if rev.len == 0 {- stdio.eprint("no working-copy commit\n", {})- } else {- stdio.eprint(- "unknown revision: {s}\n",- {str.view(rev.ptr, rev.len as i64)}- )- }- store.close(st)- txn.abort(tx)- return 1- }-- val existing = find_tag(tx.view, name)- val changed: mut bool = true- if existing is some idx {- val to = @get(tx.view.tags, idx)- if to is some t {- if objid.Id.eql(t.target, target) {- changed = false- } else {- t.target = copy_id(target)- }- }- } else {- val t: mut ref view.TagRef = @alloc(@sizeof(view.TagRef)) as ref view.TagRef- t.name = bytes.Bytes.dup(name)- t.target = copy_id(target)- @append(tx.view.tags, t)- viewops.sort_tags(tx.view.tags)- }-- if !changed {- msg.info_prefix()- stdio.print(- "tag {s} is already at {s}\n",- {str.view(name.ptr, name.len as i64), short_commit(target, 0)}- )- store.close(st)- txn.abort(tx)- free_id(target)- return 0- }-- viewops.rebuild_heads(tx.view)- val description: bytes.Bytes = make_description(bytes.bytes(c"tag set", 7), name)- val status: i32 = txn.finish(tx, description)- if status == 0 {- msg.info_prefix()- stdio.print(- "tag {s} set to {s}\n",- {str.view(name.ptr, name.len as i64), short_commit(target, 0)}- )- }- val dp: mut ref void = description.ptr as ref void- @free(dp)- store.close(st)- free_id(target)- return status-}--fn run_delete(repo: layout.Repo, args: list[ref u8], start: usize) i32 = trust {- val name: mut bytes.Bytes = bytes.empty()- 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)})- return 1- } else {- if name.len > 0 {- msg.error_prefix()- stdio.eprint("tag rm accepts exactly one name\n", {})- return 1- }- name = bytes.from_cstr(a)- }- }- i++- }- if name.len == 0 {- msg.error_prefix()- stdio.eprint("tag rm requires a name\n", {})- return 1- }-- 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 existing = find_tag(tx.view, name)- val idx: mut usize = 0- val mut_found: mut bool = false- if existing is some i2 {- idx = i2- mut_found = true- }- if !mut_found {- msg.error_prefix()- stdio.eprint(- "no such tag: {s}\n",- {str.view(name.ptr, name.len as i64)}- )- txn.abort(tx)- return 1- }- val _ = @remove(tx.view.tags, idx)- viewops.rebuild_heads(tx.view)- val description: bytes.Bytes = make_description(bytes.bytes(c"tag delete", 10), name)- val status: i32 = txn.finish(tx, description)- if status == 0 {- msg.info_prefix()- stdio.print("deleted tag {s}\n", {str.view(name.ptr, name.len as i64)})- }- val dp: mut ref void = description.ptr as ref void- @free(dp)- return status-}--fn run_list(repo: layout.Repo, args: list[ref u8], start: usize) i32 = trust {- 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"-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 {- msg.error_prefix()- stdio.eprint("tag ls takes no operands\n", {})- return 1- }- }- i++- }- 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()- val have_wc: mut bool = false- if wc_opt is some id {- wc = id- have_wc = true- }- val w_commit: usize = 12- val w_change: usize = 8- val w_name: mut usize = 3- for t in v.tags {- if t.name.len > w_name {- w_name = t.name.len- }- }- if col_titles {- print_cell(str.from_cstr(c"Tag"), w_name)- stdio.print(" ", {})- print_cell(str.from_cstr(c"Commit"), w_commit)- stdio.print(" ", {})- print_cell(str.from_cstr(c"Change"), w_change)- stdio.print(" Target\n", {})- }- for t in v.tags {- val name_z: bytes.Bytes = dup_z(t.name)- print_cell(str.view(name_z.ptr, name_z.len as i64), w_name)- stdio.print(" ", {})- val current: bool = have_wc && objid.Id.eql(t.target, wc)- val commit_z: bytes.Bytes = dup_z(- bytes.bytes(short_commit(t.target, 0).ptr, 12)- )- val change_z: mut bytes.Bytes = bytes.empty()- val lc_opt = graph.load_commit(st.handles, t.target)- if lc_opt is some lc {- change_z = short_change(lc.c.change_id)- graph.free_loaded(lc)- }- print_cell(str.view(commit_z.ptr, commit_z.len as i64), w_commit)- stdio.print(" ", {})- print_cell(str.view(change_z.ptr, change_z.len as i64), w_change)- stdio.print(" ", {})- if current {- terminal.print(str.from_cstr(c"@"), terminal.Color.Red)- }- stdio.print("\n", {})- val np: mut ref void = name_z.ptr as ref void- @free(np)- val cp: mut ref void = commit_z.ptr as ref void- @free(cp)- if change_z.ptr != none {- val chp: mut ref void = change_z.ptr as ref void- @free(chp)- }- }- if @len(v.tags) == 0 {- msg.info_prefix()- stdio.print("no tags\n", {})- }- if have_wc {- free_id(wc)- }- view.free_view(v)- store.close(st)- return 0-}--fn run_latest(repo: layout.Repo, args: list[ref u8], start: usize) i32 = trust {- val i: mut usize = start- for i < @len(args) {- val o = @get(args, i)- if o is some _ {- msg.error_prefix()- stdio.eprint("tag latest takes no operands\n", {})- return 1- }- i++- }- 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- }- }- if @len(v.tags) == 0 {- view.free_view(v)- store.close(st)- msg.error_prefix()- stdio.eprint("no tags\n", {})- return 1- }-- val best_name: mut bytes.Bytes = bytes.empty()- val best_time: mut i64 = -9223372036854775807- for t in v.tags {- val time: mut i64 = -9223372036854775807- val lc_opt = graph.load_commit(st.handles, t.target)- if lc_opt is some lc {- time = lc.c.committer.seconds- graph.free_loaded(lc)- }- val better: bool = best_name.len == 0 || time > best_time- || (time == best_time && natural_compare(t.name, best_name) > 0)- if better {- best_name = t.name- best_time = time- }- }- val out: bytes.Bytes = dup_z(best_name)- stdio.print("{s}\n", {str.view(out.ptr, out.len as i64)})- val op: mut ref void = out.ptr as ref void- @free(op)- view.free_view(v)- store.close(st)- return 0-}--fn usage() void = trust {- stdio.puts("usage: vn tag <set|ls|rm|latest> ...")- stdio.puts("")- stdio.puts("manage named pointers to commits (tags)")- stdio.puts("")- stdio.puts("subcommands:")- stdio.puts(" set <name> [-rev <rev>] create or move a tag (default: @)")- stdio.puts(" ls [-no-col-titles] list tags")- stdio.puts(" rm <name> delete a tag")- stdio.puts(" latest print the latest tag name")-}--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 => {- usage()- return 1- }- }- if cmd_is(sub, c"help", 4) || cmd_is(sub, c"-h", 2) {- usage()- return 0- }- val repo_opt = layout.discover(str.from_cstr(c"."))- 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\n", {})- return 1- }- }- val status: mut i32 = 1- if cmd_is(sub, c"set", 3) {- status = run_set(repo, args, start + 1)- } elif cmd_is(sub, c"ls", 2) || cmd_is(sub, c"list", 4) {- status = run_list(repo, args, start + 1)- } elif cmd_is(sub, c"rm", 2) || cmd_is(sub, c"remove", 6) {- status = run_delete(repo, args, start + 1)- } elif cmd_is(sub, c"latest", 6) {- status = run_latest(repo, args, start + 1)- } else {- msg.error_prefix()- stdio.eprint("unknown tag subcommand: {s}\n", {str.from_cstr(sub)})- usage()- }- layout.free_repo(repo)- return status-}--- a/veins/src/cli/whoami_cmd.sx+++ /dev/null@@ -1,118 +0,0 @@-/// `vn whoami`: report the role and fingerprint granted by a server.--val stdio = use("std/stdio")-val str = use("std/string")-val bytes = use("../core/bytes.sx")-val layout = use("../store/layout.sx")-val remote_config = use("../git/remote.sx")-val credentials = use("../auth/credentials.sx")-val ed = use("../crypto/ed25519.sx")-val client = use("../protocol/client.sx")-val cmsg = use("../core/msg.sx")--fn role_text(role: u8) bytes.Bytes = {- if role == 2 {- return bytes.bytes(c"write", 5)- }- if role == 1 {- return bytes.bytes(c"read", 4)- }- return bytes.bytes(c"anonymous", 9)-}--pub fn run(args: list[ref u8], start: usize) i32 = trust {- val arg_opt = @get(args, start)- val remote: mut bytes.Bytes = bytes.Bytes.dup(bytes.bytes(c"origin", 6))- val url: mut bytes.Bytes = bytes.empty()- val key: mut bytes.Bytes = bytes.empty()- val repo_name: mut bytes.Bytes = bytes.empty()- val pin: mut bytes.Bytes = bytes.empty()- if arg_opt is some a {- val av: bytes.Bytes = bytes.from_cstr(a)- if bytes.Bytes.starts_with(av, bytes.bytes(c"file://", 7))- || bytes.Bytes.starts_with(av, bytes.bytes(c"ssh://", 6))- || bytes.Bytes.starts_with(av, bytes.bytes(c"veins://", 8)) {- url = bytes.Bytes.dup(av)- repo_name = client.url_repo_name(url)- } else {- remote = bytes.Bytes.dup(av)- }- }- if url.ptr == none {- val repo_opt = layout.discover(str.from_cstr(c"."))- if repo_opt is none {- cmsg.error_prefix()- stdio.eprint("not a veins repository\n", {})- return 1- }- val repo: mut layout.Repo = layout.Repo{root: bytes.empty()}- match repo_opt {- some r => {- repo = r- }- none => {- return 1- }- }- val u = remote_config.url_of(repo, remote)- if u is none {- cmsg.error_prefix()- stdio.eprint("unknown remote\n", {})- layout.free_repo(repo)- return 1- }- if u is some v {- url = v- }- val kn = remote_config.key_name_of(repo, remote)- if kn is some k {- if credentials.local_key_exists(k) {- key = k- } else {- bytes.free_owned(k)- }- }- val pn = remote_config.tls_pin_of(repo, remote)- if pn is some pv {- pin = pv- }- repo_name = client.url_repo_name(url)- layout.free_repo(repo)- }- if key.ptr == none {- val fallback = credentials.key_for_url(url)- if fallback is some ck {- key = ck- }- }- val w = client.whoami_pinned(url, key, repo_name, pin)- if url.ptr != none {- bytes.free_owned(url)- }- if key.ptr != none {- bytes.free_owned(key)- }- if repo_name.ptr != none {- bytes.free_owned(repo_name)- }- if remote.ptr != none {- bytes.free_owned(remote)- }- if w is some v {- stdio.print("role: {s}\n", {str.view(role_text(v.role).ptr, role_text(v.role).len as i64)})- val fp_text: bytes.Bytes = ed.base32_text(v.fingerprint)- stdio.print("fingerprint: {s}\n", {str.view(fp_text.ptr, fp_text.len as i64)})- bytes.free_owned(fp_text)- bytes.free_ptr(v.fingerprint.ptr)- return 0- }- val detail: bytes.Bytes = client.last_connect_error()- cmsg.error_prefix()- if detail.len > 0 {- stdio.eprint("{s}\n", {str.view(detail.ptr, detail.len as i64)})- } else {- stdio.eprint("cannot authenticate\n", {})- }- bytes.free_owned(detail)- return 1-}--- a/veins/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/veins/src/core/bytes.sx+++ /dev/null@@ -1,157 +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-}--/// Release an owned byte span (frees the pointer, not the descriptor).-pub fn free_owned(b: Bytes) void = {- if b.ptr != none {- val p: mut ref void = b.ptr as ref void- trust @free(p)- }-}--/// Free a raw owned pointer.-pub fn free_ptr(p: ref u8) void = {- if p != none {- val q: mut ref void = p as ref void- trust @free(q)- }-}--- a/veins/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/veins/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/veins/src/core/identity.sx+++ /dev/null@@ -1,151 +0,0 @@-/// Author/committer identity from repository config, the user config at-/// `~/.local/config/veins/veins.toml`, or the 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")-val userconfig = use("userconfig.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,- want_name: bool,- env1: ref u8,- env2: ref u8-) bytes.Bytes = trust {- val c = config_value(repo, key)- if c is some v {- return v- }- val u: mut option[bytes.Bytes] = none- if want_name {- u = userconfig.author_name()- } else {- u = userconfig.author_email()- }- if u 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),- true,- c"GIT_AUTHOR_NAME",- c"USER"- )- val email: bytes.Bytes = first_config(- repo,- bytes.bytes(c"user.email", 10),- false,- 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/veins/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/veins/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/veins/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/veins/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/veins/src/core/repoconfig.sx+++ /dev/null@@ -1,223 +0,0 @@-/// Repository-local configuration (`key = value` lines in `.veins/config`).-///-/// The file is intentionally simple so that local configuration can be read by-/// every command without a dependency on a TOML parser. Values are returned as-/// owned byte spans; callers release them with `bytes.free`-style helpers.--val bytes = use("bytes.sx")-val buf = use("buf.sx")-val str = use("std/string")-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 strip_comment(b: bytes.Bytes) bytes.Bytes = trust {- val i: mut usize = 0- for i < b.len {- if bytes.Bytes.at(b, i) == 35 {- return trim(bytes.Bytes.slice(b, 0, i))- }- i++- }- return trim(b)-}--/// Look up one key. The result is owned by the caller.-pub fn get(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)- val data: mut bytes.Bytes = bytes.empty()- match data_opt {- some d => {- data = d- }- none => {- return none- }- }- 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 && 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 = strip_comment(- 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-}--pub fn free_value(v: bytes.Bytes) void = trust {- files.free_buffer(v)-}--fn is_true(v: bytes.Bytes) bool = trust {- return bytes.Bytes.eql(v, bytes.bytes(c"true", 4))- || bytes.Bytes.eql(v, bytes.bytes(c"1", 1))- || bytes.Bytes.eql(v, bytes.bytes(c"yes", 3))- || bytes.Bytes.eql(v, bytes.bytes(c"on", 2))-}--/// Read a boolean key. Missing values use `default`.-pub fn get_bool(repo: layout.Repo, key: bytes.Bytes, default: bool) bool = trust {- val v = get(repo, key)- match v {- some value => {- val out: bool = is_true(value)- files.free_buffer(value)- return out- }- none => {- return default- }- }-}--/// Read a text key. The result is owned by the caller.-pub fn get_text(repo: layout.Repo, key: bytes.Bytes) option[bytes.Bytes] = trust {- return get(repo, key)-}--pub fn current_bookmark(repo: layout.Repo) option[bytes.Bytes] = trust {- return get(repo, bytes.bytes(c"bookmark.current", 16))-}--pub fn set_current_bookmark(repo: layout.Repo, name: bytes.Bytes) bool = trust {- return set(repo, bytes.bytes(c"bookmark.current", 16), name)-}--pub fn clear_current_bookmark(repo: layout.Repo) bool = trust {- return remove(repo, bytes.bytes(c"bookmark.current", 16))-}--/// Set a key, replacing an existing value. The file is rewritten atomically.-pub fn set(repo: layout.Repo, key: bytes.Bytes, value: bytes.Bytes) bool = trust {- val path: str.StringView = layout.config_path(repo)- val data_opt = files.read_all(path)- val b: mut buf.Buf = buf.new(256)- if data_opt is some d {- val pos: mut usize = 0- val start: mut usize = 0- for pos <= d.len {- if pos == d.len || bytes.Bytes.at(d, pos) == 10 {- val line: bytes.Bytes = bytes.Bytes.slice(d, start, pos)- val t: bytes.Bytes = trim(line)- val eq: i64 = index_of(t, 61)- val is_key: bool = eq >= 0 && bytes.Bytes.eql(- trim(bytes.Bytes.slice(t, 0, eq as usize)),- key- )- if !is_key {- buf.Buf.put_bytes(b, line)- if pos < d.len {- buf.Buf.put_u8(b, 10)- }- }- start = pos + 1- }- pos++- }- files.free_buffer(d)- }- buf.Buf.put_bytes(b, key)- buf.Buf.put_raw(b, c" = " as ref u8, 3)- buf.Buf.put_bytes(b, value)- buf.Buf.put_u8(b, 10)- val out: bytes.Bytes = bytes.Bytes.dup(buf.Buf.view(b))- buf.Buf.free(b)- val passed: bool = files.write_all(path, out)- files.free_buffer(out)- files.free_path(path)- return passed-}--fn index_of(b: bytes.Bytes, needle: u8) i64 = trust {- val i: mut usize = 0- for i < b.len {- if bytes.Bytes.at(b, i) == needle {- return i as i64- }- i++- }- return -1-}--/// Remove a key from the configuration.-pub fn remove(repo: layout.Repo, key: bytes.Bytes) bool = trust {- val path: str.StringView = layout.config_path(repo)- val data_opt = files.read_all(path)- val b: mut buf.Buf = buf.new(256)- if data_opt is some d {- val pos: mut usize = 0- val start: mut usize = 0- for pos <= d.len {- if pos == d.len || bytes.Bytes.at(d, pos) == 10 {- val line: bytes.Bytes = bytes.Bytes.slice(d, start, pos)- val t: bytes.Bytes = trim(line)- val eq: i64 = index_of(t, 61)- val is_key: bool = eq >= 0 && bytes.Bytes.eql(- trim(bytes.Bytes.slice(t, 0, eq as usize)),- key- )- if !is_key {- buf.Buf.put_bytes(b, line)- if pos < d.len {- buf.Buf.put_u8(b, 10)- }- }- start = pos + 1- }- pos++- }- files.free_buffer(d)- }- val out: bytes.Bytes = bytes.Bytes.dup(buf.Buf.view(b))- buf.Buf.free(b)- val passed: bool = files.write_all(path, out)- files.free_buffer(out)- files.free_path(path)- return passed-}--- a/veins/src/core/userconfig.sx+++ /dev/null@@ -1,422 +0,0 @@-/// User-level configuration from `~/.local/config/veins/veins.toml`.-///-/// The file is optional. The only table currently understood is `[user]`:-///-/// [user]-/// name = "Your Name"-/// email = "you@example.com"-///-/// Values are returned as owned byte spans so callers can hand them to the-/// same signature path used for repository configuration and environment-/// overrides.--val str = use("std/string")-val fs = use("std/fs")-val bytes = use("../core/bytes.sx")-val buf = use("../core/buf.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_path() option[str.StringView] = trust {- val home = fs.home_dir_cstr()- match home {- some h => {- return some files.join3(- str.from_cstr(h),- str.from_cstr(c".local/config/veins"),- str.from_cstr(c"veins.toml")- )- }- none => {- return none- }- }-}--/// Remove a trailing TOML comment that is outside a quoted string.-fn strip_comment(v: bytes.Bytes) bytes.Bytes = trust {- val i: mut usize = 0- val in_double: mut bool = false- val in_single: mut bool = false- val escaped: mut bool = false- for i < v.len {- val c: u8 = bytes.Bytes.at(v, i)- if in_double {- if escaped {- escaped = false- } elif c == 92 {- escaped = true- } elif c == 34 {- in_double = false- }- } elif in_single {- if c == 39 {- in_single = false- }- } elif c == 34 {- in_double = true- } elif c == 39 {- in_single = true- } elif c == 35 {- return trim(bytes.Bytes.slice(v, 0, i))- }- i++- }- return trim(v)-}--/// Decode a TOML string value. Unquoted values are accepted as a convenience.-fn unquote(v: bytes.Bytes) option[bytes.Bytes] = trust {- if v.len >= 2 {- val first: u8 = bytes.Bytes.at(v, 0)- val last: u8 = bytes.Bytes.at(v, v.len - 1)- if first == 39 && last == 39 {- return some(bytes.Bytes.dup(bytes.Bytes.slice(v, 1, v.len - 1)))- }- if first == 34 && last == 34 {- val inner: bytes.Bytes = bytes.Bytes.slice(v, 1, v.len - 1)- val out: mut buf.Buf = buf.new(inner.len + 1)- val i: mut usize = 0- for i < inner.len {- val c: u8 = bytes.Bytes.at(inner, i)- if c == 92 && i + 1 < inner.len {- val next: u8 = bytes.Bytes.at(inner, i + 1)- if next == 34 {- buf.Buf.put_u8(out, 34)- } elif next == 92 {- buf.Buf.put_u8(out, 92)- } elif next == 110 {- buf.Buf.put_u8(out, 10)- } elif next == 114 {- buf.Buf.put_u8(out, 13)- } elif next == 116 {- buf.Buf.put_u8(out, 9)- } else {- buf.Buf.put_u8(out, 92)- buf.Buf.put_u8(out, next)- }- i = i + 2- } else {- buf.Buf.put_u8(out, c)- i++- }- }- val result: bytes.Bytes = bytes.Bytes.dup(buf.Buf.view(out))- buf.Buf.free(out)- return some(result)- }- }- if v.len == 0 {- return none- }- return some(bytes.Bytes.dup(v))-}--fn key_matches(key: bytes.Bytes, in_user: bool, want_name: bool) bool = trust {- if in_user {- if want_name {- return bytes.Bytes.eql(key, bytes.bytes(c"name", 4))- }- return bytes.Bytes.eql(key, bytes.bytes(c"email", 5))- }- if want_name {- return bytes.Bytes.eql(key, bytes.bytes(c"user.name", 9))- }- return bytes.Bytes.eql(key, bytes.bytes(c"user.email", 10))-}--fn scan(data: bytes.Bytes, want_name: bool) option[bytes.Bytes] = trust {- val in_user: mut bool = false- 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 raw: bytes.Bytes = bytes.Bytes.slice(data, start, pos)- val line: bytes.Bytes = trim(raw)- if line.len > 0 && bytes.Bytes.at(line, 0) != 35 {- if bytes.Bytes.at(line, 0) == 91 {- val close: mut i64 = -1- val j: mut usize = 1- for j < line.len {- if bytes.Bytes.at(line, j) == 93 {- close = j as i64- break- }- j++- }- if close > 0 {- val table: bytes.Bytes = trim(- bytes.Bytes.slice(line, 1, close as usize)- )- in_user = bytes.Bytes.eql(table, bytes.bytes(c"user", 4))- }- } else {- val eq: mut i64 = -1- val k: mut usize = 0- for k < line.len {- if bytes.Bytes.at(line, k) == 61 {- eq = k as i64- break- }- k++- }- if eq >= 0 {- val key: bytes.Bytes = trim(- bytes.Bytes.slice(line, 0, eq as usize)- )- if key_matches(key, in_user, want_name) {- val raw_value: bytes.Bytes = strip_comment(- trim(bytes.Bytes.slice(line, eq as usize + 1, line.len))- )- val decoded = unquote(raw_value)- if decoded is some value {- if value.len > 0 {- return some value- }- }- }- }- }- }- start = pos + 1- }- pos++- }- return none-}--fn read_value(want_name: bool) option[bytes.Bytes] = trust {- val path_opt = config_path()- val path: mut str.StringView = str.view(none, 0)- match path_opt {- some p => {- path = p- }- none => {- return none- }- }- 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 none- }- }- val out: option[bytes.Bytes] = scan(data, want_name)- files.free_buffer(data)- return out-}--/// The configured author name, if the user file exists and defines one.-pub fn author_name() option[bytes.Bytes] = trust {- return read_value(true)-}--/// The configured author email, if the user file exists and defines one.-pub fn author_email() option[bytes.Bytes] = trust {- return read_value(false)-}---fn ensure_config_dir() bool = trust {- val home = fs.home_dir_cstr()- match home {- some h => {- val base: str.StringView = str.from_cstr(h)- val local: str.StringView = files.join(- base,- str.from_cstr(c".local")- )- val config: str.StringView = files.join(- local,- str.from_cstr(c"config")- )- val dir: str.StringView = files.join(- config,- str.from_cstr(c"veins")- )- val made_local: bool = files.exists_dir(local)- || files.mkdir_all(local)- val made_config: bool = made_local- && (files.exists_dir(config) || files.mkdir_all(config))- val made_dir: bool = made_config- && (files.exists_dir(dir) || files.mkdir_all(dir))- files.free_path(local)- files.free_path(config)- files.free_path(dir)- return made_dir- }- none => {- return false- }- }-}--fn update_value(key: bytes.Bytes, value: bytes.Bytes, clear: bool) bool = trust {- val want_name: bool = bytes.Bytes.eql(key, bytes.bytes(c"user.name", 9))- val want_email: bool = bytes.Bytes.eql(key, bytes.bytes(c"user.email", 10))- if !want_name && !want_email {- return false- }- val path_opt = config_path()- val path: mut str.StringView = str.view(none, 0)- match path_opt {- some p => {- path = p- }- none => {- return false- }- }- if !ensure_config_dir() {- files.free_path(path)- return false- }-- val kept: mut buf.Buf = buf.new(256)- val data_opt = files.read_all(path)- if data_opt is some data {- val in_user: mut bool = false- 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 = bytes.Bytes.slice(data, start, pos)- val t: bytes.Bytes = trim(line)- val keep: mut bool = true- if t.len > 0 && bytes.Bytes.at(t, 0) == 91 {- val close: mut i64 = -1- val j: mut usize = 1- for j < t.len {- if bytes.Bytes.at(t, j) == 93 {- close = j as i64- break- }- j++- }- if close > 0 {- val table: bytes.Bytes = trim(- bytes.Bytes.slice(t, 1, close as usize)- )- in_user = bytes.Bytes.eql(table, bytes.bytes(c"user", 4))- }- } elif t.len > 0 && bytes.Bytes.at(t, 0) != 35 {- val eq: mut i64 = -1- val k: mut usize = 0- for k < t.len {- if bytes.Bytes.at(t, k) == 61 {- eq = k as i64- break- }- k++- }- if eq >= 0 {- val name: bytes.Bytes = trim(- bytes.Bytes.slice(t, 0, eq as usize)- )- if in_user {- if (want_name- && bytes.Bytes.eql(name, bytes.bytes(c"name", 4)))- || (want_email- && bytes.Bytes.eql(name, bytes.bytes(c"email", 5))) {- keep = false- }- } else {- if (want_name- && bytes.Bytes.eql(name, bytes.bytes(c"user.name", 9)))- || (want_email- && bytes.Bytes.eql(- name,- bytes.bytes(c"user.email", 10)- )) {- keep = false- }- }- }- }- if keep {- buf.Buf.put_bytes(kept, line)- if !at_end {- buf.Buf.put_u8(kept, 10)- }- }- start = pos + 1- }- pos++- }- files.free_buffer(data)- }-- val final: mut buf.Buf = buf.new(kept.len + 64)- if !clear {- if want_name {- buf.Buf.put_bytes(final, bytes.bytes(c"user.name", 9))- } else {- buf.Buf.put_bytes(final, bytes.bytes(c"user.email", 10))- }- buf.Buf.put_bytes(final, bytes.bytes(c" = \"", 4))- val i: mut usize = 0- for i < value.len {- val c: u8 = bytes.Bytes.at(value, i)- if c == 34 {- buf.Buf.put_bytes(final, bytes.bytes(c"\\\"", 2))- } elif c == 92 {- buf.Buf.put_bytes(final, bytes.bytes(c"\\\\", 2))- } elif c == 10 {- buf.Buf.put_bytes(final, bytes.bytes(c"\\n", 2))- } elif c == 13 {- buf.Buf.put_bytes(final, bytes.bytes(c"\\r", 2))- } elif c == 9 {- buf.Buf.put_bytes(final, bytes.bytes(c"\\t", 2))- } else {- buf.Buf.put_u8(final, c)- }- i++- }- buf.Buf.put_bytes(final, bytes.bytes(c"\"\n", 2))- }- buf.Buf.put_bytes(final, buf.Buf.view(kept))- val out: bytes.Bytes = bytes.Bytes.dup(buf.Buf.view(final))- val wrote: bool = files.write_all(path, out)- files.free_buffer(out)- buf.Buf.free(final)- buf.Buf.free(kept)- files.free_path(path)- return wrote-}--/// Set a user-level identity key (`user.name` or `user.email`).-pub fn set(key: bytes.Bytes, value: bytes.Bytes) bool = trust {- return update_value(key, value, false)-}--/// Remove a user-level identity key.-pub fn remove(key: bytes.Bytes) bool = trust {- return update_value(key, bytes.empty(), true)-}--- a/veins/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/veins/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/veins/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/veins/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/veins/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/veins/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/veins/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/veins/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/veins/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/veins/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/veins/src/crypto/blake3/blake3_neon.c+++ /dev/null@@ -1,367 +0,0 @@-#include "blake3_impl.h"--#include <arm_neon.h>--#ifdef __ARM_BIG_ENDIAN-#error "This implementation only supports little-endian ARM."-// It might be that all we need for big-endian support here is to get the loads-// and stores right, but step zero would be finding a way to test it in CI.-#endif--INLINE uint32x4_t loadu_128(const uint8_t src[16]) {- // vld1q_u32 has alignment requirements. Don't use it.- return vreinterpretq_u32_u8(vld1q_u8(src));-}--INLINE void storeu_128(uint32x4_t src, uint8_t dest[16]) {- // vst1q_u32 has alignment requirements. Don't use it.- vst1q_u8(dest, vreinterpretq_u8_u32(src));-}--INLINE uint32x4_t add_128(uint32x4_t a, uint32x4_t b) {- return vaddq_u32(a, b);-}--INLINE uint32x4_t xor_128(uint32x4_t a, uint32x4_t b) {- return veorq_u32(a, b);-}--INLINE uint32x4_t set1_128(uint32_t x) { return vld1q_dup_u32(&x); }--INLINE uint32x4_t set4(uint32_t a, uint32_t b, uint32_t c, uint32_t d) {- uint32_t array[4] = {a, b, c, d};- return vld1q_u32(array);-}--INLINE uint32x4_t rot16_128(uint32x4_t x) {- // The straightforward implementation would be two shifts and an or, but that's- // slower on microarchitectures we've tested. See- // https://github.com/BLAKE3-team/BLAKE3/pull/319.- // return vorrq_u32(vshrq_n_u32(x, 16), vshlq_n_u32(x, 32 - 16));- return vreinterpretq_u32_u16(vrev32q_u16(vreinterpretq_u16_u32(x)));-}--INLINE uint32x4_t rot12_128(uint32x4_t x) {- // See comment in rot16_128.- // return vorrq_u32(vshrq_n_u32(x, 12), vshlq_n_u32(x, 32 - 12));- return vsriq_n_u32(vshlq_n_u32(x, 32-12), x, 12);-}--INLINE uint32x4_t rot8_128(uint32x4_t x) {- // See comment in rot16_128.- // return vorrq_u32(vshrq_n_u32(x, 8), vshlq_n_u32(x, 32 - 8));-#if defined(__clang__)- return vreinterpretq_u32_u8(__builtin_shufflevector(vreinterpretq_u8_u32(x), vreinterpretq_u8_u32(x), 1,2,3,0,5,6,7,4,9,10,11,8,13,14,15,12));-#elif __GNUC__ * 10000 + __GNUC_MINOR__ * 100 >=40700- static const uint8x16_t r8 = {1,2,3,0,5,6,7,4,9,10,11,8,13,14,15,12};- return vreinterpretq_u32_u8(__builtin_shuffle(vreinterpretq_u8_u32(x), vreinterpretq_u8_u32(x), r8));-#else - return vsriq_n_u32(vshlq_n_u32(x, 32-8), x, 8);-#endif-}--INLINE uint32x4_t rot7_128(uint32x4_t x) {- // See comment in rot16_128.- // return vorrq_u32(vshrq_n_u32(x, 7), vshlq_n_u32(x, 32 - 7));- return vsriq_n_u32(vshlq_n_u32(x, 32-7), x, 7);-}--// TODO: compress_neon--// TODO: hash2_neon--/*- * ----------------------------------------------------------------------------- * hash4_neon- * ----------------------------------------------------------------------------- */--INLINE void round_fn4(uint32x4_t v[16], uint32x4_t 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(uint32x4_t vecs[4]) {- // Individually transpose the four 2x2 sub-matrices in each corner.- uint32x4x2_t rows01 = vtrnq_u32(vecs[0], vecs[1]);- uint32x4x2_t rows23 = vtrnq_u32(vecs[2], vecs[3]);-- // Swap the top-right and bottom-left 2x2s (which just got transposed).- vecs[0] =- vcombine_u32(vget_low_u32(rows01.val[0]), vget_low_u32(rows23.val[0]));- vecs[1] =- vcombine_u32(vget_low_u32(rows01.val[1]), vget_low_u32(rows23.val[1]));- vecs[2] =- vcombine_u32(vget_high_u32(rows01.val[0]), vget_high_u32(rows23.val[0]));- vecs[3] =- vcombine_u32(vget_high_u32(rows01.val[1]), vget_high_u32(rows23.val[1]));-}--INLINE void transpose_msg_vecs4(const uint8_t *const *inputs,- size_t block_offset, uint32x4_t out[16]) {- out[0] = loadu_128(&inputs[0][block_offset + 0 * sizeof(uint32x4_t)]);- out[1] = loadu_128(&inputs[1][block_offset + 0 * sizeof(uint32x4_t)]);- out[2] = loadu_128(&inputs[2][block_offset + 0 * sizeof(uint32x4_t)]);- out[3] = loadu_128(&inputs[3][block_offset + 0 * sizeof(uint32x4_t)]);- out[4] = loadu_128(&inputs[0][block_offset + 1 * sizeof(uint32x4_t)]);- out[5] = loadu_128(&inputs[1][block_offset + 1 * sizeof(uint32x4_t)]);- out[6] = loadu_128(&inputs[2][block_offset + 1 * sizeof(uint32x4_t)]);- out[7] = loadu_128(&inputs[3][block_offset + 1 * sizeof(uint32x4_t)]);- out[8] = loadu_128(&inputs[0][block_offset + 2 * sizeof(uint32x4_t)]);- out[9] = loadu_128(&inputs[1][block_offset + 2 * sizeof(uint32x4_t)]);- out[10] = loadu_128(&inputs[2][block_offset + 2 * sizeof(uint32x4_t)]);- out[11] = loadu_128(&inputs[3][block_offset + 2 * sizeof(uint32x4_t)]);- out[12] = loadu_128(&inputs[0][block_offset + 3 * sizeof(uint32x4_t)]);- out[13] = loadu_128(&inputs[1][block_offset + 3 * sizeof(uint32x4_t)]);- out[14] = loadu_128(&inputs[2][block_offset + 3 * sizeof(uint32x4_t)]);- out[15] = loadu_128(&inputs[3][block_offset + 3 * sizeof(uint32x4_t)]);- 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,- uint32x4_t *out_low, uint32x4_t *out_high) {- uint64_t mask = (increment_counter ? ~0 : 0);- *out_low = set4(- counter_low(counter + (mask & 0)), counter_low(counter + (mask & 1)),- counter_low(counter + (mask & 2)), counter_low(counter + (mask & 3)));- *out_high = set4(- counter_high(counter + (mask & 0)), counter_high(counter + (mask & 1)),- counter_high(counter + (mask & 2)), counter_high(counter + (mask & 3)));-}--static void blake3_hash4_neon(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) {- uint32x4_t 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]),- };- uint32x4_t 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;- }- uint32x4_t block_len_vec = set1_128(BLAKE3_BLOCK_LEN);- uint32x4_t block_flags_vec = set1_128(block_flags);- uint32x4_t msg_vecs[16];- transpose_msg_vecs4(inputs, block * BLAKE3_BLOCK_LEN, msg_vecs);-- uint32x4_t 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(uint32x4_t)]);- storeu_128(h_vecs[4], &out[1 * sizeof(uint32x4_t)]);- storeu_128(h_vecs[1], &out[2 * sizeof(uint32x4_t)]);- storeu_128(h_vecs[5], &out[3 * sizeof(uint32x4_t)]);- storeu_128(h_vecs[2], &out[4 * sizeof(uint32x4_t)]);- storeu_128(h_vecs[6], &out[5 * sizeof(uint32x4_t)]);- storeu_128(h_vecs[3], &out[6 * sizeof(uint32x4_t)]);- storeu_128(h_vecs[7], &out[7 * sizeof(uint32x4_t)]);-}--/*- * ----------------------------------------------------------------------------- * hash_many_neon- * ----------------------------------------------------------------------------- */--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);--INLINE void hash_one_neon(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;- }- // TODO: Implement compress_neon. However note that according to- // https://github.com/BLAKE2/BLAKE2/commit/7965d3e6e1b4193438b8d3a656787587d2579227,- // compress_neon might not be any faster than compress_portable.- blake3_compress_in_place_portable(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_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) {- while (num_inputs >= 4) {- blake3_hash4_neon(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_neon(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/veins/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/veins/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/veins/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/veins/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/veins/src/crypto/ed25519.sx+++ /dev/null@@ -1,266 +0,0 @@-/// Ed25519 signatures, key encoding, and fingerprints.-///-/// The primitives are provided by OpenSSL through the native shim.--val bytes = use("../core/bytes.sx")-val b3 = use("blake3.sx")--pub val SEED_LEN: usize = 32-pub val PUBLIC_LEN: usize = 32-pub val SIGNATURE_LEN: usize = 64-pub val FINGERPRINT_LEN: usize = 16--extern (C) fn vn_ed25519_public_from_seed(seed: ref u8, public_out: ref u8) i32 =-"vn_ed25519_public_from_seed"-extern (C) fn vn_ed25519_sign(- seed: ref u8,- msg: ref u8,- msg_len: usize,- sig: ref u8-) i32 = "vn_ed25519_sign"-extern (C) fn vn_ed25519_verify(- public_key: ref u8,- msg: ref u8,- msg_len: usize,- sig: ref u8-) i32 = "vn_ed25519_verify"--pub fn public_from_seed(seed: bytes.Bytes) option[bytes.Bytes] = trust {- if seed.len != SEED_LEN {- return none- }- val out: ref u8 = @alloc(PUBLIC_LEN) as ref u8- if vn_ed25519_public_from_seed(seed.ptr, out) != 1 {- @free(out as ref void)- return none- }- return some bytes.bytes(out, PUBLIC_LEN)-}--pub fn sign(seed: bytes.Bytes, msg: bytes.Bytes) option[bytes.Bytes] = trust {- if seed.len != SEED_LEN {- return none- }- val out: ref u8 = @alloc(SIGNATURE_LEN) as ref u8- if vn_ed25519_sign(seed.ptr, msg.ptr, msg.len, out) != 1 {- @free(out as ref void)- return none- }- return some bytes.bytes(out, SIGNATURE_LEN)-}--pub fn verify(public_key: bytes.Bytes, msg: bytes.Bytes, sig: bytes.Bytes) bool = trust {- if public_key.len != PUBLIC_LEN || sig.len != SIGNATURE_LEN {- return false- }- return vn_ed25519_verify(public_key.ptr, msg.ptr, msg.len, sig.ptr) == 1-}--fn alphabet() ref u8 = {- return c"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"-}--/// The raw 16-byte fingerprint for a public key.-pub fn fingerprint_bytes(public_key: bytes.Bytes) option[bytes.Bytes] = trust {- if public_key.len != PUBLIC_LEN {- return none- }- val input: ref u8 = @alloc(12 + PUBLIC_LEN) as ref u8- @memcpy(input as ref void, c"veins/key/1", 12)- @memcpy(@ptradd(input, 12) as ref void, public_key.ptr as ref void, PUBLIC_LEN)- val digest: ref u8 = @alloc(32) as ref u8- b3.hash(input, 12 + PUBLIC_LEN, digest)- @free(input as ref void)- val out: ref u8 = @alloc(FINGERPRINT_LEN) as ref u8- @memcpy(out as ref void, digest as ref void, FINGERPRINT_LEN)- @free(digest as ref void)- return some bytes.bytes(out, FINGERPRINT_LEN)-}--/// The 26-character lowercase base32 fingerprint, NUL terminated.-pub fn fingerprint(public_key: bytes.Bytes) option[bytes.Bytes] = trust {- val raw_opt = fingerprint_bytes(public_key)- val raw: mut bytes.Bytes = bytes.empty()- match raw_opt {- some r => {- raw = r- }- none => {- return none- }- }- val out: ref u8 = @alloc(27) as ref u8- val bits: mut u64 = 0- val nbits: mut usize = 0- val oi: mut usize = 0- val ri: mut usize = 0- for ri < raw.len {- val b: u8 = bytes.Bytes.at(raw, ri)- bits = (bits << 8) | (b as u64)- nbits = nbits + 8- for nbits >= 5 {- nbits = nbits - 5- val idx: usize = ((bits >> (nbits as u64)) & 31) as usize- @store8(@ptradd(out, oi as i64), @load8(@ptradd(alphabet(), idx as i64)))- oi++- }- ri++- }- if nbits > 0 {- val idx2: usize = ((bits << (5 - nbits)) & 31) as usize- @store8(@ptradd(out, oi as i64), @load8(@ptradd(alphabet(), idx2 as i64)))- oi++- }- @store8(@ptradd(out, oi as i64), 0)- bytes.free_owned(raw)- return some bytes.bytes(out, oi)-}--fn b64_value(c: u8) i32 = {- if c >= 65 && c <= 90 {- return (c - 65) as i32- }- if c >= 97 && c <= 122 {- return (c - 71) as i32- }- if c >= 48 && c <= 57 {- return (c + 4) as i32- }- if c == 45 {- return 62- }- if c == 95 {- return 63- }- return -1-}--fn b64_char(v: u8) u8 = {- if v < 26 {- return (65 + v) as u8- }- if v < 52 {- return (97 + v - 26) as u8- }- if v < 62 {- return (48 + v - 52) as u8- }- if v == 62 {- return 45- }- return 95-}--/// Decode unpadded base64url. The result is owned by the caller.-pub fn base64url_decode(text: bytes.Bytes) option[bytes.Bytes] = trust {- if text.len == 0 {- return none- }- val out: ref u8 = @alloc(text.len + 1) as ref u8- val acc: mut u32 = 0- val bits: mut usize = 0- val oi: mut usize = 0- val i: mut usize = 0- for i < text.len {- val v: i32 = b64_value(bytes.Bytes.at(text, i))- if v < 0 {- @free(out as ref void)- return none- }- acc = (acc << 6) | (v as u32)- bits = bits + 6- if bits >= 8 {- bits = bits - 8- @store8(@ptradd(out, oi as i64), ((acc >> (bits as u32)) & 255) as u8)- oi++- }- i++- }- return some bytes.bytes(out, oi)-}--/// Encode as unpadded base64url. The result is owned by the caller.-pub fn base64url_encode(data: bytes.Bytes) bytes.Bytes = trust {- val out: ref u8 = @alloc((data.len * 4) / 3 + 5) as ref u8- val acc: mut u32 = 0- val bits: mut usize = 0- val oi: mut usize = 0- val di: mut usize = 0- for di < data.len {- val b: u8 = bytes.Bytes.at(data, di)- acc = (acc << 8) | (b as u32)- bits = bits + 8- for bits >= 6 {- bits = bits - 6- @store8(@ptradd(out, oi as i64), b64_char(((acc >> (bits as u32)) & 63) as u8))- oi++- }- di++- }- if bits > 0 {- @store8(@ptradd(out, oi as i64), b64_char(((acc << (6 - bits)) & 63) as u8))- oi++- }- @store8(@ptradd(out, oi as i64), 0)- return bytes.bytes(out, oi)-}--/// Parse `ed25519:<base64url>` into raw public key bytes.-pub fn parse_public(text: bytes.Bytes) option[bytes.Bytes] = trust {- val prefix: bytes.Bytes = bytes.bytes(c"ed25519:", 8)- if !bytes.Bytes.starts_with(text, prefix) {- return none- }- val encoded: bytes.Bytes = bytes.Bytes.slice(text, 8, text.len)- val decoded = base64url_decode(encoded)- match decoded {- some raw => {- if raw.len != PUBLIC_LEN {- bytes.free_owned(raw)- return none- }- return some raw- }- none => {- return none- }- }-}--/// Render a public key as `ed25519:<base64url>`. The result is owned.-pub fn format_public(public_key: bytes.Bytes) bytes.Bytes = trust {- val enc: bytes.Bytes = base64url_encode(public_key)- val out: ref u8 = @alloc(8 + enc.len) as ref u8- @memcpy(out as ref void, c"ed25519:", 8)- @memcpy(@ptradd(out, 8) as ref void, enc.ptr as ref void, enc.len)- bytes.free_owned(enc)- return bytes.bytes(out, 8 + enc.len)-}--/// Lowercase unpadded base32 text for raw bytes. The result is owned.-pub fn base32_text(raw: bytes.Bytes) bytes.Bytes = trust {- val out: ref u8 = @alloc((raw.len * 8) / 5 + 4) as ref u8- val bits: mut u64 = 0- val nbits: mut usize = 0- val oi: mut usize = 0- val ri: mut usize = 0- for ri < raw.len {- val b: u8 = bytes.Bytes.at(raw, ri)- bits = (bits << 8) | (b as u64)- nbits = nbits + 8- for nbits >= 5 {- nbits = nbits - 5- val idx: usize = ((bits >> (nbits as u64)) & 31) as usize- @store8(@ptradd(out, oi as i64), @load8(@ptradd(alphabet(), idx as i64)))- oi++- }- ri++- }- if nbits > 0 {- val idx2: usize = ((bits << (5 - nbits)) & 31) as usize- @store8(@ptradd(out, oi as i64), @load8(@ptradd(alphabet(), idx2 as i64)))- oi++- }- @store8(@ptradd(out, oi as i64), 0)- return bytes.bytes(out, oi)-}--- a/veins/src/crypto/openssl_c.c+++ /dev/null@@ -1,205 +0,0 @@-/* OpenSSL-backed primitives for veins: Ed25519, TLS 1.3, and TCP connect. */--#include <stddef.h>-#include <stdint.h>-#include <string.h>-#include <stdio.h>--#include <openssl/evp.h>-#include <openssl/ssl.h>-#include <openssl/err.h>-#include <openssl/x509.h>--#include <sys/types.h>-#include <sys/socket.h>-#include <netdb.h>-#include <unistd.h>-#include <sys/stat.h>--int vn_ed25519_public_from_seed(const unsigned char *seed, unsigned char *pub) {- EVP_PKEY *pkey = EVP_PKEY_new_raw_private_key(EVP_PKEY_ED25519, NULL, seed, 32);- if (!pkey) return 0;- size_t len = 32;- int ok = EVP_PKEY_get_raw_public_key(pkey, pub, &len);- EVP_PKEY_free(pkey);- return ok == 1 && len == 32;-}--int vn_ed25519_sign(const unsigned char *seed, const unsigned char *msg,- size_t msg_len, unsigned char *sig) {- EVP_PKEY *pkey = EVP_PKEY_new_raw_private_key(EVP_PKEY_ED25519, NULL, seed, 32);- if (!pkey) return 0;- EVP_MD_CTX *ctx = EVP_MD_CTX_new();- if (!ctx) { EVP_PKEY_free(pkey); return 0; }- int ok = 0;- size_t sig_len = 64;- if (EVP_DigestSignInit(ctx, NULL, NULL, NULL, pkey) == 1) {- if (EVP_DigestSign(ctx, sig, &sig_len, msg, msg_len) == 1 && sig_len == 64) ok = 1;- }- EVP_MD_CTX_free(ctx);- EVP_PKEY_free(pkey);- return ok;-}--int vn_ed25519_verify(const unsigned char *pub, const unsigned char *msg,- size_t msg_len, const unsigned char *sig) {- EVP_PKEY *pkey = EVP_PKEY_new_raw_public_key(EVP_PKEY_ED25519, NULL, pub, 32);- if (!pkey) return 0;- EVP_MD_CTX *ctx = EVP_MD_CTX_new();- if (!ctx) { EVP_PKEY_free(pkey); return 0; }- int ok = 0;- if (EVP_DigestVerifyInit(ctx, NULL, NULL, NULL, pkey) == 1) {- if (EVP_DigestVerify(ctx, sig, 64, msg, msg_len) == 1) ok = 1;- }- EVP_MD_CTX_free(ctx);- EVP_PKEY_free(pkey);- return ok;-}--static void vn_ssl_error(char *err, size_t cap) {- if (!err || cap == 0) {- ERR_clear_error();- return;- }- unsigned long code = ERR_get_error();- if (code == 0) {- if (cap > 0) err[0] = 0;- return;- }- ERR_error_string_n(code, err, cap);-}--void *vn_tls_server_ctx(const char *cert, const char *key) {- SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());- if (!ctx) return NULL;- if (SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION) != 1) goto fail;- if (SSL_CTX_use_certificate_chain_file(ctx, cert) != 1) goto fail;- if (SSL_CTX_use_PrivateKey_file(ctx, key, SSL_FILETYPE_PEM) != 1) goto fail;- if (SSL_CTX_check_private_key(ctx) != 1) goto fail;- return ctx;-fail:- SSL_CTX_free(ctx);- return NULL;-}--void *vn_tls_client_ctx(void) {- SSL_CTX *ctx = SSL_CTX_new(TLS_client_method());- if (!ctx) return NULL;- if (SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION) != 1) {- SSL_CTX_free(ctx);- return NULL;- }- SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);- if (SSL_CTX_set_default_verify_paths(ctx) != 1) {- SSL_CTX_free(ctx);- return NULL;- }- return ctx;-}--void *vn_tls_client_ctx_pinned(void) {- SSL_CTX *ctx = SSL_CTX_new(TLS_client_method());- if (!ctx) return NULL;- if (SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION) != 1) {- SSL_CTX_free(ctx);- return NULL;- }- SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL);- return ctx;-}--void *vn_tls_accept(void *ctx, int fd, char *err, size_t err_cap) {- SSL *ssl = SSL_new((SSL_CTX *)ctx);- if (!ssl) { vn_ssl_error(err, err_cap); return NULL; }- SSL_set_fd(ssl, fd);- if (SSL_accept(ssl) != 1) {- vn_ssl_error(err, err_cap);- SSL_free(ssl);- return NULL;- }- return ssl;-}--void *vn_tls_connect(void *ctx, int fd, const char *host, char *err, size_t err_cap) {- SSL *ssl = SSL_new((SSL_CTX *)ctx);- if (!ssl) { vn_ssl_error(err, err_cap); return NULL; }- SSL_set_fd(ssl, fd);- if (host && host[0]) {- SSL_set_tlsext_host_name(ssl, host);- SSL_set1_host(ssl, host);- }- if (SSL_connect(ssl) != 1) {- vn_ssl_error(err, err_cap);- SSL_free(ssl);- return NULL;- }- return ssl;-}--long vn_tls_read(void *ssl, void *buf, size_t len) {- int n = SSL_read((SSL *)ssl, buf, (int)len);- if (n <= 0) return -1;- return n;-}--long vn_tls_write(void *ssl, const void *buf, size_t len) {- int n = SSL_write((SSL *)ssl, buf, (int)len);- if (n <= 0) return -1;- return n;-}--int vn_tls_exporter(void *ssl, unsigned char *out, size_t len) {- static const char label[] = "EXPORTER-veins-auth/1";- return SSL_export_keying_material((SSL *)ssl, out, len, label,- sizeof(label) - 1, NULL, 0, 0) == 1;-}--int vn_tls_peer_sha256(void *ssl, unsigned char out[32]) {- X509 *cert = SSL_get1_peer_certificate((SSL *)ssl);- if (!cert) return 0;- unsigned int len = 0;- int ok = X509_digest(cert, EVP_sha256(), out, &len) == 1 && len == 32;- X509_free(cert);- return ok;-}--void vn_tls_free(void *ssl) {- if (!ssl) return;- SSL_shutdown((SSL *)ssl);- SSL_free((SSL *)ssl);-}--void vn_tls_ctx_free(void *ctx) {- if (ctx) SSL_CTX_free((SSL_CTX *)ctx);-}--int vn_tcp_connect(const char *host, int port) {- struct addrinfo hints;- struct addrinfo *res = NULL;- char service[16];- memset(&hints, 0, sizeof(hints));- hints.ai_family = AF_UNSPEC;- hints.ai_socktype = SOCK_STREAM;- snprintf(service, sizeof(service), "%d", port);- if (getaddrinfo(host, service, &hints, &res) != 0) return -1;- int fd = -1;- for (struct addrinfo *it = res; it != NULL; it = it->ai_next) {- fd = socket(it->ai_family, it->ai_socktype, it->ai_protocol);- if (fd < 0) continue;- if (connect(fd, it->ai_addr, it->ai_addrlen) == 0) break;- close(fd);- fd = -1;- }- freeaddrinfo(res);- return fd;-}--int vn_file_mode(const char *path) {- struct stat st;- if (stat(path, &st) != 0) return -1;- return (int)(st.st_mode & 07777);-}--int vn_chmod(const char *path, int mode) {- return chmod(path, (mode_t)mode);-}--- a/veins/src/crypto/tls.sx+++ /dev/null@@ -1,140 +0,0 @@-/// TLS 1.3 transport and TCP connection helpers backed by OpenSSL.--val bytes = use("../core/bytes.sx")--pub val ERR_CAP: usize = 256--extern (C) fn vn_tls_server_ctx(cert: ref u8, key: ref u8) ref void = "vn_tls_server_ctx"-extern (C) fn vn_tls_client_ctx() ref void = "vn_tls_client_ctx"-extern (C) fn vn_tls_client_ctx_pinned() ref void = "vn_tls_client_ctx_pinned"-extern (C) fn vn_tls_accept(- ctx: ref void,- fd: i32,- errbuf: ref u8,- errcap: usize-) ref void = "vn_tls_accept"-extern (C) fn vn_tls_connect(- ctx: ref void,- fd: i32,- host: ref u8,- errbuf: ref u8,- errcap: usize-) ref void = "vn_tls_connect"-extern (C) fn vn_tls_read(ssl: ref void, buf: ref void, len: usize) i64 = "vn_tls_read"-extern (C) fn vn_tls_write(ssl: ref void, buf: ref void, len: usize) i64 = "vn_tls_write"-extern (C) fn vn_tls_exporter(ssl: ref void, out: ref u8, len: usize) i32 =-"vn_tls_exporter"-extern (C) fn vn_tls_peer_sha256(ssl: ref void, out: ref u8) i32 = "vn_tls_peer_sha256"-extern (C) fn vn_tls_free(ssl: ref void) void = "vn_tls_free"-extern (C) fn vn_tls_ctx_free(ctx: ref void) void = "vn_tls_ctx_free"-extern (C) fn vn_tcp_connect(host: ref u8, port: i32) i32 = "vn_tcp_connect"-extern (C) fn vn_file_mode(path: ref u8) i32 = "vn_file_mode"-extern (C) fn vn_chmod(path: ref u8, mode: i32) i32 = "vn_chmod"--pub type Conn = {- fd: mut i32- ssl: mut ref void- secure: mut bool-}--pub fn server_ctx(cert: ref u8, key: ref u8) ref void = trust {- return vn_tls_server_ctx(cert, key)-}--pub fn client_ctx() ref void = trust {- return vn_tls_client_ctx()-}--pub fn client_ctx_pinned() ref void = trust {- return vn_tls_client_ctx_pinned()-}--pub fn accept(ctx: ref void, fd: i32) ref void = trust {- return vn_tls_accept(ctx, fd, none, 0)-}--pub fn connect(ctx: ref void, fd: i32, host: ref u8) ref void = trust {- return vn_tls_connect(ctx, fd, host, none, 0)-}--pub fn read(ssl: ref void, buf: ref u8, n: usize) i64 = trust {- return vn_tls_read(ssl, buf as ref void, n)-}--pub fn write(ssl: ref void, buf: ref u8, n: usize) i64 = trust {- return vn_tls_write(ssl, buf as ref void, n)-}--pub fn exporter(ssl: ref void, out: ref u8, n: usize) bool = trust {- return vn_tls_exporter(ssl, out, n) == 1-}--pub fn peer_sha256(ssl: ref void, out: ref u8) bool = trust {- return vn_tls_peer_sha256(ssl, out) == 1-}--pub fn free(ssl: ref void) void = trust {- vn_tls_free(ssl)-}--pub fn free_ctx(ctx: ref void) void = trust {- vn_tls_ctx_free(ctx)-}--pub fn tcp_connect(host: ref u8, port: i32) i32 = trust {- return vn_tcp_connect(host, port)-}--pub fn file_mode(path: ref u8) i32 = trust {- return vn_file_mode(path)-}--pub fn chmod(path: ref u8, mode: i32) i32 = trust {- return vn_chmod(path, mode)-}--pub fn to_hex(data: bytes.Bytes) bytes.Bytes = trust {- val out: ref u8 = @alloc(data.len * 2 + 1) as ref u8- val hex: ref u8 = c"0123456789abcdef"- val i: mut usize = 0- for i < data.len {- val v: u8 = bytes.Bytes.at(data, i)- @store8(@ptradd(out, (i * 2) as i64), @load8(@ptradd(hex, ((v >> 4) as i64))))- @store8(@ptradd(out, (i * 2 + 1) as i64), @load8(@ptradd(hex, ((v & 15) as i64))))- i++- }- @store8(@ptradd(out, (data.len * 2) as i64), 0)- return bytes.bytes(out, data.len * 2)-}--/// Compare two hex digests, ignoring colons and case.-pub fn hex_equal(a: bytes.Bytes, b: bytes.Bytes) bool = trust {- val ai: mut usize = 0- val bi: mut usize = 0- for {- for ai < a.len && bytes.Bytes.at(a, ai) == 58 {- ai++- }- for bi < b.len && bytes.Bytes.at(b, bi) == 58 {- bi++- }- if ai >= a.len || bi >= b.len {- return ai >= a.len && bi >= b.len- }- val ca: u8 = lower(bytes.Bytes.at(a, ai))- val cb: u8 = lower(bytes.Bytes.at(b, bi))- if ca != cb {- return false- }- ai++- bi++- }- return true-}--fn lower(c: u8) u8 = {- if c >= 65 && c <= 90 {- return (c + 32) as u8- }- return c-}--- a/veins/src/git/export.sx+++ /dev/null@@ -1,1125 +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.--link "-lz"--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,- @addr(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 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 {- // The entry takes ownership of the child OID allocation; it is- // released once, with the entry, in the cleanup below.- @append(- entries,- tree.entry(bytes.Bytes.dup(e.name), e.kind, objid.id(co.ptr))- )- } 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)- 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)- 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 = copy_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) {- if m.id.ptr != none {- @free(m.id.ptr as ref void)- }- @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))- if m.id.ptr != none {- @free(m.id.ptr as ref void)- }- @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-}--fn ensure_dir(path: str.StringView) bool = trust {- if files.exists_dir(path) {- return true- }- return files.mkdir_all(path)-}--/// A native repository has no `.veins/git` until an import. Export can create a-/// minimal bare repository so history can leave veins without first running-/// git or an import.-fn ensure_mirror(repo: layout.Repo) bool = trust {- val gitp: str.StringView = layout.git_dir(repo)- val objects: str.StringView = files.join(gitp, str.from_cstr(c"objects"))- val refs: str.StringView = files.join(gitp, str.from_cstr(c"refs"))- val refs_heads: str.StringView = files.join(refs, str.from_cstr(c"heads"))- val refs_tags: str.StringView = files.join(refs, str.from_cstr(c"tags"))- val good: bool = ensure_dir(gitp)- && ensure_dir(objects)- && ensure_dir(refs)- && ensure_dir(refs_heads)- && ensure_dir(refs_tags)- val head: str.StringView = files.join(gitp, str.from_cstr(c"HEAD"))- if good && !files.exists_file(head) {- val _ = files.write_all(head, bytes.from_cstr(c"ref: refs/heads/main\n"))- }- val config: str.StringView = files.join(gitp, str.from_cstr(c"config"))- if good && !files.exists_file(config) {- val body: bytes.Bytes = bytes.from_cstr(c"[core]\n\trepositoryformatversion = 0\n\tfilemode = true\n\tbare = true\n")- val _ = files.write_all(config, body)- }- files.free_path(config)- files.free_path(head)- files.free_path(objects)- files.free_path(refs)- files.free_path(refs_heads)- files.free_path(refs_tags)- files.free_path(gitp)- return good-}--pub fn run(repo: layout.Repo) i32 = trust {- if !ensure_mirror(repo) {- msg.error_prefix()- stdio.eprint("cannot create git mirror\n", {})- return 1- }- val gitp: str.StringView = layout.git_dir(repo)- val git_opt = object.open(gitp)- val git_repo: mut object.GitRepo = @zeroed- val git_open: mut bool = false- match git_opt {- ok g => {- // object.open takes ownership of the path on success.- git_repo = g- git_open = true- }- err _ => {- files.free_path(gitp)- }- }-- 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 => {- oidmap.free(commits)- commits = m- }- err _ => {- }- }- match trees_opt {- ok m => {- oidmap.free(trees)- trees = m- }- err _ => {- }- }- match blobs_opt {- ok m => {- oidmap.free(blobs)- 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 {- // The exporter inserts through `ctx`, which owns the maps that grew- // during export. The initial locals are only a starting snapshot.- val sc = gitmap.save_map(repo, str.from_cstr(c"commits"), ctx.commits)- val stree = gitmap.save_map(repo, str.from_cstr(c"trees"), ctx.trees)- val sblob = gitmap.save_map(repo, str.from_cstr(c"blobs"), ctx.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(ctx.commits)- oidmap.free(ctx.trees)- oidmap.free(ctx.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/veins/src/git/format.sx+++ /dev/null@@ -1,660 +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 {- if c.tree.ptr != none {- val tp: mut ref void = c.tree.ptr as ref void- @free(tp)- }- 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/veins/src/git/import.sx+++ /dev/null@@ -1,1587 +0,0 @@-link "-lz"--/// 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 random = use("std/crypto/random")-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 graph = use("../object/graph.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 txn = use("../store/txn.sx")-val viewops = use("../store/viewops.sx")-val identity = use("../core/identity.sx")-val repoconfig = use("../core/repoconfig.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")-val checkout = use("../worktree/checkout.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 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)- }- format.free_parsed_tree(parsed)- object.free_object(obj)- return some id-}--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_remote_ref(- v: mut ref view.View,- remote: bytes.Bytes,- name: bytes.Bytes,- id: objid.Id-) void = trust {- val i: mut usize = 0- for i < @len(v.remote_refs) {- val o = @get(v.remote_refs, i)- if o is some rr {- if bytes.Bytes.eql(rr.remote, remote) && bytes.Bytes.eql(rr.name, name) {- rr.target = id- return- }- }- i++- }- val rr: mut ref view.RemoteRef = @alloc(@sizeof(view.RemoteRef)) as ref view.RemoteRef- rr.remote = bytes.Bytes.dup(remote)- rr.name = bytes.Bytes.dup(name)- rr.target = id- @append(v.remote_refs, rr)-}--fn sort_remote_refs(xs: mut list[ref view.RemoteRef]) 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.RemoteRef = 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.RemoteRef = none- if prev_opt is some v2 {- prev = v2- }- val cmp: i64 = bytes.Bytes.cmp(prev.remote, c.remote)- val ord: mut i64 = cmp- if cmp == 0 {- ord = bytes.Bytes.cmp(prev.name, c.name)- }- if ord <= 0 {- break- }- @set(xs, j, prev)- j--- }- @set(xs, j, c)- i++- }-}--fn var_has_bookmark(v: mut ref view.View, name: bytes.Bytes, id: objid.Id) void = 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++- }- set_bookmark(v, name, id)-}--type RemoteSplit = {- remote: mut bytes.Bytes- name: mut bytes.Bytes-}--fn split_remote(full: bytes.Bytes) RemoteSplit = trust {- val i: mut usize = 0- for i < full.len {- if bytes.Bytes.at(full, i) == 47 {- return RemoteSplit{- remote: bytes.Bytes.slice(full, 0, i),- name: bytes.Bytes.slice(full, i + 1, full.len)- }- }- i++- }- return RemoteSplit{- remote: bytes.Bytes.dup(full),- name: bytes.Bytes.dup(bytes.bytes(c"main", 4))- }-}--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, free_names: bool) void = trust {- @listfree(v.heads)- for bm in v.bookmarks {- @listfree(bm.targets.adds)- @listfree(bm.targets.removes)- if free_names && bm.name.ptr != none {- val np: mut ref void = bm.name.ptr as ref void- @free(np)- }- val bp: mut ref void = bm as ref void- @free(bp)- }- @listfree(v.bookmarks)- for t in v.tags {- if free_names && t.name.ptr != none {- val np: mut ref void = t.name.ptr as ref void- @free(np)- }- val tp: mut ref void = t as ref void- @free(tp)- }- @listfree(v.tags)- for rr in v.remote_refs {- if free_names {- if rr.remote.ptr != none {- val rp: mut ref void = rr.remote.ptr as ref void- @free(rp)- }- if rr.name.ptr != none {- val np: mut ref void = rr.name.ptr as ref void- @free(np)- }- }- val rp2: mut ref void = rr as ref void- @free(rp2)- }- @listfree(v.remote_refs)- for w in v.working_copies {- if free_names && w.workspace.ptr != none {- val wp2: mut ref void = w.workspace.ptr as ref void- @free(wp2)- }- val wp: mut ref void = w as ref void- @free(wp)- }- @listfree(v.working_copies)- if v.owned.ptr != none {- val ob: mut ref void = v.owned.ptr as ref void- @free(ob)- }- @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)-}--fn pick_current_branch(- branches: list[ref ImportNamedTarget],- head_commit: option[bytes.Bytes]-) option[bytes.Bytes] = trust {- val fallback: mut option[bytes.Bytes] = none- if head_commit is some hc {- for b in branches {- if bytes.Bytes.eql(b.oid, hc) {- if bytes.Bytes.eql(b.name, bytes.bytes(c"main", 4))- || bytes.Bytes.eql(b.name, bytes.bytes(c"master", 6)) {- return some b.name- }- if fallback is none {- fallback = some b.name- }- }- }- if fallback is some f {- return some f- }- }- for b in branches {- if bytes.Bytes.eql(b.name, bytes.bytes(c"main", 4))- || bytes.Bytes.eql(b.name, bytes.bytes(c"master", 6)) {- return some b.name- }- }- if @len(branches) > 0 {- val first = @get(branches, 0)- if first is some b {- return some b.name- }- }- return none-}--fn apply_current_bookmark(- repo: layout.Repo,- branches: list[ref ImportNamedTarget],- head_commit: option[bytes.Bytes]-) void = trust {- val current = pick_current_branch(branches, head_commit)- if current is some name {- val _ = repoconfig.set_current_bookmark(repo, name)- } else {- val _ = repoconfig.clear_current_bookmark(repo)- }-}---/// Flush object batches as packs during large imports to bound peak memory.-fn working_tree_empty(repo: layout.Repo) bool = trust {- val names: list[ref u8] = files.list_dir(layout.root_view(repo))- val empty: mut bool = true- for name in names {- if !bytes.Bytes.eql(bytes.from_cstr(name), bytes.bytes(c".veins", 6)) {- empty = false- }- }- files.free_names(names)- return empty-}--/// Create an empty-message working-copy commit on top of an imported head so-/// snapshots amend the working copy instead of rewriting the imported branch.-fn create_working_copy(repo: layout.Repo, parent: objid.Id) 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 handles: list[ref store.Handle] = txn.handles(tx)- val loaded = graph.load_commit(handles, parent)- val root_tree: mut objid.Id = objid.id_none()- match loaded {- some lc => {- root_tree = graph.copy_id(lc.c.root_tree)- graph.free_loaded(lc)- }- none => {- msg.error_prefix()- stdio.eprint("cannot read imported commit\n", {})- txn.abort(tx)- 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 parents: mut list[objid.Id] = lists.new[objid.Id]()- @append(parents, parent)- 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)- viewops.remove_head(tx.view, parent)- viewops.set_workspace(tx.view, new_id)- viewops.rebuild_heads(tx.view)- val status: i32 = txn.finish(tx, bytes.bytes(c"import", 6))- @listfree(parents)- @listfree(renames)- @listfree(extra)- @free(nc as ref void)- identity.free_sig(sig)- @free(cid as ref void)- if root_tree.ptr != none {- val rtp: mut ref void = root_tree.ptr as ref void- @free(rtp)- }- if new_id.ptr != none {- val np: mut ref void = new_id.ptr as ref void- @free(np)- }- return status-}--pub fn run(repo: layout.Repo) i32 = trust {- val checkout_after: bool = working_tree_empty(repo)- 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 => {- oidmap.free(commits_map)- commits_map = m- }- err _ => {- maps_ok = false- }- }- match trees_map_opt {- ok m2 => {- oidmap.free(trees_map)- trees_map = m2- }- err _ => {- maps_ok = false- }- }- match blobs_map_opt {- ok m3 => {- oidmap.free(blobs_map)- 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 remotes: 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))- }- }- for rr in refset.remotes {- val peeled3 = peel_to_commit(ctx.git, rr.oid)- if peeled3 is some c3 {- add_branch_target(remotes, rr.name, c3)- @append(tips, bytes.Bytes.dup(c3))- }- }- 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)- free_named_targets(remotes)- if head_commit is some h2 {- val hp: mut ref void = h2.ptr as ref void- @free(hp)- }- refs.free(refset)- writer.abort(ctx.writer)- 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)- }- if cid_out.ptr != none {- val co: mut ref void = cid_out.ptr as ref void- @free(co)- }- 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)- free_named_targets(remotes)- if head_commit is some h3 {- val hp2: mut ref void = h3.ptr as ref void- @free(hp2)- }- refs.free(refset)- writer.abort(ctx.writer)- 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)- free_named_targets(remotes)- if head_commit is some h4 {- val hp3: mut ref void = h4.ptr as ref void- @free(hp3)- }- refs.free(refset)- writer.abort(ctx.writer)- 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()- val view_from_store: mut bool = false- match current {- some cv => {- v = cv- view_from_store = true- 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)- }- }- for r in remotes {- val id = get_id(ctx.commits_map, r.oid)- if id is some rid {- val parts = split_remote(r.name)- set_remote_ref(v, parts.remote, parts.name, rid)- var_has_bookmark(v, parts.name, rid)- }- }- sort_bookmarks(v.bookmarks)- sort_tags(v.tags)- sort_remote_refs(v.remote_refs)-- @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)- }- }- for r in remotes {- val id = get_id(ctx.commits_map, r.oid)- if id is some rid {- add_unique_head(new_heads, rid)- }- }- 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 = dup_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 checkout_after || !view_from_store {- 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)- }- apply_current_bookmark(repo, branches, head_commit)- clear_view_view(v, !view_from_store)- free_commit_records(records)- free_named_targets(branches)- free_named_targets(tags)- free_named_targets(remotes)- if head_commit is some h5 {- val hp4: mut ref void = h5.ptr as ref void- @free(hp4)- }- refs.free(refset)- writer.abort(ctx.writer)- 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- op.owned = bytes.empty()- val op_body: bytes.Bytes = operation.encode(op)- val op_id: objid.Id = append_object(ctx, types.OPERATION, op_body)- @listfree(op.tags)- @free(cmd_kv as ref void)- @free(op as ref void)- if view_id.ptr != none {- val vp: mut ref void = view_id.ptr as ref void- @free(vp)- }- 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) == 0- 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, !view_from_store)- 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)- free_named_targets(remotes)- if head_commit is some h6 {- val hp6: mut ref void = h6.ptr as ref void- @free(hp6)- }- if op_id.ptr != none {- val oip: mut ref void = op_id.ptr as ref void- @free(oip)- }- 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)- }- }- apply_current_bookmark(repo, branches, head_commit)- }-- 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, !view_from_store)- 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)- free_named_targets(remotes)- if head_commit is some h7 {- val hp7: mut ref void = h7.ptr as ref void- @free(hp7)- }- if op_id.ptr != none {- val oip2: mut ref void = op_id.ptr as ref void- @free(oip2)- }- 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)- val work_copy_status: mut i32 = 0- if head_ok && checkout_after && !objid.Id.is_none(head_id) {- work_copy_status = create_working_copy(repo, head_id)- }- if head_id.ptr != none {- val hip: mut ref void = head_id.ptr as ref void- @free(hip)- }- if !head_ok {- return 1- }- if work_copy_status != 0 {- msg.error_prefix()- stdio.eprint(- "imported history; cannot create working copy (code {d})\n",- {work_copy_status}- )- return 1- }- if checkout_after {- val status: i32 = checkout.materialize_working_copy(repo)- if status != 0 {- msg.error_prefix()- stdio.eprint("imported history; checkout failed (code {d})\n", {status})- 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/veins/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/veins/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/veins/src/git/materialize.sx+++ /dev/null@@ -1,808 +0,0 @@-/// Replace lazy git-backed blobs with canonical chunked veins blobs.-///-/// Materialization rewrites the trees, conflict objects, commits, and view-/// reachable from the current view. Objects without lazy descendants keep-/// their existing IDs.--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 types = use("../object/types.sx")-val raw = use("../object/raw.sx")-val blob = use("../object/blob.sx")-val tree = use("../object/tree.sx")-val commit = use("../object/commit.sx")-val conflict = use("../object/conflict.sx")-val view = use("../object/view.sx")-val graph = use("../object/graph.sx")-val content = use("../object/content.sx")-val store = use("../store/store.sx")-val state = use("../store/state.sx")-val txn = use("../store/txn.sx")-val layout = use("../store/layout.sx")-val idmap = use("../store/idmap.sx")-val files = use("../io/files.sx")-val object = use("object.sx")-val lazy = use("lazy.sx")-val gitmap = use("map.sx")-val oidmap = use("oidmap.sx")-val refmap = use("refmap.sx")-val checkout = use("../worktree/checkout.sx")--type RawSave = {- id: mut objid.Id- body: mut bytes.Bytes-}--type MatCtx = {- repo: layout.Repo- tx: mut ref txn.Txn- handles: list[ref store.Handle]- git: mut object.GitRepo- has_git: mut bool- trees: mut refmap.RefMap- blobs: mut refmap.RefMap- commits: mut refmap.RefMap- conflicts: mut refmap.RefMap- raw_saves: mut list[ref RawSave]- new_commits: mut usize- new_trees: mut usize- new_blobs: mut usize- changed: 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 free_id(id: objid.Id) void = trust {- if id.ptr != none {- val p: mut ref void = id.ptr as ref void- @free(p)- }-}--fn free_ids(ids: list[objid.Id]) void = trust {- for id in ids {- free_id(id)- }- @listfree(ids)-}--fn map_get(map: refmap.RefMap, id: objid.Id) option[objid.Id] = trust {- val got = refmap.get(map, bytes.bytes(id.ptr, 32))- match got {- some v => {- // Copy the value: growing the map later must not invalidate IDs- // already handed to tree entries, commits, or the view.- val out: ref u8 = @alloc(32) as ref u8- @memcpy(out as ref void, v.ptr as ref void, 32)- return some objid.id(out)- }- none => {- return none- }- }-}--fn map_put(map: mut refmap.RefMap, old_id: objid.Id, new_id: objid.Id) void = trust {- refmap.put(map, bytes.bytes(old_id.ptr, 32), bytes.bytes(new_id.ptr, 32))-}--fn mapped_commit(ctx: MatCtx, id: objid.Id) objid.Id = trust {- val got = map_get(ctx.commits, id)- if got is some mapped {- return mapped- }- return id-}--fn record_raw(ctx: mut MatCtx, old_id: objid.Id, new_id: objid.Id) void = trust {- val raw_opt = gitmap.load_raw(ctx.repo, old_id)- if raw_opt is some body {- val rs: mut ref RawSave = @alloc(@sizeof(RawSave)) as ref RawSave- rs.id = copy_id(new_id)- rs.body = body- @append(ctx.raw_saves, rs)- }-}--fn free_raw_saves(xs: list[ref RawSave]) void = trust {- for rs in xs {- if rs.body.ptr != none {- val bp: mut ref void = rs.body.ptr as ref void- @free(bp)- }- if rs.id.ptr != none {- val ip: mut ref void = rs.id.ptr as ref void- @free(ip)- }- val rp: mut ref void = rs as ref void- @free(rp)- }- @listfree(xs)-}--fn ordered_commits(- handles: list[ref store.Handle],- roots: list[objid.Id]-) list[objid.Id] = trust {- val stack: mut list[ref Mark] = lists.new[ref Mark]()- for r in roots {- val m: mut ref Mark = @alloc(@sizeof(Mark)) as ref Mark- m.id = copy_id(r)- m.expanded = false- @append(stack, m)- }- val visited: mut idmap.IdSet = idmap.new(64)- val out: mut list[objid.Id] = lists.new[objid.Id]()- for @len(stack) > 0 {- val m: mut ref Mark = @remove(stack, @len(stack) - 1)- if idmap.contains(visited, bytes.bytes(m.id.ptr, 32)) {- free_id(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 {- for p in lc.c.parents {- if !idmap.contains(visited, bytes.bytes(p.ptr, 32)) {- val pm: mut ref Mark = @alloc(@sizeof(Mark)) as ref Mark- pm.id = copy_id(p)- pm.expanded = false- @append(stack, pm)- }- }- graph.free_loaded(lc)- }- } else {- val _ = idmap.put(visited, bytes.bytes(m.id.ptr, 32))- @append(out, copy_id(m.id))- free_id(m.id)- @free(m as ref void)- }- }- idmap.free(visited)- @listfree(stack)- return out-}--fn materialize_blob(ctx: mut MatCtx, old_id: objid.Id) objid.Id = trust {- val existing = map_get(ctx.blobs, old_id)- if existing is some id {- return id- }- if !lazy.is_lazy(old_id) {- map_put(ctx.blobs, old_id, old_id)- return old_id- }- val data_opt = content.read_blob(ctx.handles, old_id, ctx.git, ctx.has_git)- val data: mut bytes.Bytes = bytes.empty()- match data_opt {- some d => {- data = d- }- none => {- return objid.id_none()- }- }- val built: ref blob.BlobBuild = blob.build(data.ptr, data.len)- val root: objid.Id = copy_id(blob.root_id(built))- val i: mut usize = 0- for i < @len(built.objects) {- val o = @get(built.objects, i)- if o is some obj {- val orf: mut ref raw.RawObject = obj- val oid: objid.Id = objid.id(orf.id)- val _ = txn.add_known(ctx.tx, orf.type_byte, oid, orf.body)- orf.body = bytes.empty()- }- i++- }- blob.free_build(built)- files.free_buffer(data)- map_put(ctx.blobs, old_id, root)- ctx.new_blobs++- ctx.changed = true- return root-}--/// Materialize one object. Kind 0 is a blob, 1 a tree, and 2 a conflict.-fn materialize_node(- ctx: mut MatCtx,- old_id: objid.Id,- kind: u8,- depth: usize-) objid.Id = trust {- if depth > 4096 {- return objid.id_none()- }- if kind == 0 {- return materialize_blob(ctx, old_id)- }- if kind == 1 {- val existing = map_get(ctx.trees, old_id)- if existing is some id {- return id- }- val body_opt = state.read_body(ctx.handles, old_id, types.TREE)- val body: mut bytes.Bytes = bytes.empty()- match body_opt {- some b => {- body = b- }- none => {- return objid.id_none()- }- }- val decoded = tree.decode(body)- val t: mut ref tree.Tree = @zeroed- match decoded {- ok v => {- t = v- }- err _ => {- files.free_buffer(body)- return objid.id_none()- }- }- val changed: mut bool = false- val ei: mut usize = 0- for ei < @len(t.entries) {- val eo = @get(t.entries, ei)- if eo is some e {- if e.kind == tree.KIND_FILE || e.kind == tree.KIND_EXECUTABLE- || e.kind == tree.KIND_SYMLINK {- if lazy.is_lazy(e.target) {- val mapped: objid.Id = materialize_node(- ctx,- e.target,- 0,- depth + 1- )- if objid.Id.is_none(mapped) {- tree.free_tree(t)- files.free_buffer(body)- return objid.id_none()- }- if !objid.Id.eql(mapped, e.target) {- e.target = mapped- changed = true- }- }- } elif e.kind == tree.KIND_SUBTREE {- val mapped: objid.Id = materialize_node(- ctx,- e.target,- 1,- depth + 1- )- if objid.Id.is_none(mapped) {- tree.free_tree(t)- files.free_buffer(body)- return objid.id_none()- }- if !objid.Id.eql(mapped, e.target) {- e.target = mapped- changed = true- }- } elif e.kind == tree.KIND_CONFLICT {- val mapped: objid.Id = materialize_node(- ctx,- e.target,- 2,- depth + 1- )- if objid.Id.is_none(mapped) {- tree.free_tree(t)- files.free_buffer(body)- return objid.id_none()- }- if !objid.Id.eql(mapped, e.target) {- e.target = mapped- changed = true- }- } elif e.kind == tree.KIND_SUBMODULE {- } else {- tree.free_tree(t)- files.free_buffer(body)- return objid.id_none()- }- }- ei++- }- val result: mut objid.Id = objid.id_none()- if changed {- val encoded = tree.encode(t.entries)- match encoded {- ok new_body => {- result = txn.add_object(ctx.tx, types.TREE, new_body)- map_put(ctx.trees, old_id, result)- ctx.new_trees++- ctx.changed = true- record_raw(ctx, old_id, result)- }- err _ => {- tree.free_tree(t)- files.free_buffer(body)- return objid.id_none()- }- }- } else {- result = old_id- map_put(ctx.trees, old_id, old_id)- }- tree.free_tree(t)- files.free_buffer(body)- return result- }- if kind == 2 {- val existing = map_get(ctx.conflicts, old_id)- if existing is some id {- return id- }- val body_opt = state.read_body(ctx.handles, old_id, types.CONFLICT)- val body: mut bytes.Bytes = bytes.empty()- match body_opt {- some b => {- body = b- }- none => {- return objid.id_none()- }- }- val decoded = conflict.decode(body)- val c: mut ref conflict.Conflict = @zeroed- match decoded {- ok v => {- c = v- }- err _ => {- files.free_buffer(body)- return objid.id_none()- }- }- val changed: mut bool = false- val vi: mut usize = 0- for vi < @len(c.adds) {- val vo = @get(c.adds, vi)- if vo is some v {- if !objid.Id.is_none(v.target) {- val target_kind: mut u8 = 0- val skip: mut bool = false- if v.kind == tree.KIND_SUBTREE {- target_kind = 1- } elif v.kind == tree.KIND_CONFLICT {- target_kind = 2- } elif v.kind == tree.KIND_SUBMODULE {- skip = true- }- if !skip {- val before: objid.Id = v.target- val mapped: objid.Id = materialize_node(- ctx,- v.target,- target_kind,- depth + 1- )- if objid.Id.is_none(mapped) {- conflict.free_conflict(c)- files.free_buffer(body)- return objid.id_none()- }- if !objid.Id.eql(before, mapped) {- v.target = mapped- changed = true- }- }- }- }- vi++- }- val ri: mut usize = 0- for ri < @len(c.removes) {- val ro = @get(c.removes, ri)- if ro is some v {- if !objid.Id.is_none(v.target) {- val target_kind: mut u8 = 0- val skip: mut bool = false- if v.kind == tree.KIND_SUBTREE {- target_kind = 1- } elif v.kind == tree.KIND_CONFLICT {- target_kind = 2- } elif v.kind == tree.KIND_SUBMODULE {- skip = true- }- if !skip {- val before: objid.Id = v.target- val mapped: objid.Id = materialize_node(- ctx,- v.target,- target_kind,- depth + 1- )- if objid.Id.is_none(mapped) {- conflict.free_conflict(c)- files.free_buffer(body)- return objid.id_none()- }- if !objid.Id.eql(before, mapped) {- v.target = mapped- changed = true- }- }- }- }- ri++- }- val result: mut objid.Id = objid.id_none()- if changed {- val encoded: bytes.Bytes = conflict.encode(c.adds, c.removes)- result = txn.add_object(ctx.tx, types.CONFLICT, encoded)- map_put(ctx.conflicts, old_id, result)- ctx.changed = true- } else {- result = old_id- map_put(ctx.conflicts, old_id, old_id)- }- conflict.free_conflict(c)- files.free_buffer(body)- return result- }- return objid.id_none()-}--fn remap_table(old_map: oidmap.OidMap, mappings: refmap.RefMap) oidmap.OidMap = trust {- val out: mut oidmap.OidMap = oidmap.new(old_map.len + 16)- val i: mut usize = 0- for i < old_map.cap {- if oidmap.slot_used(old_map, i) {- val key: bytes.Bytes = oidmap.slot_oid(old_map, i)- val value: bytes.Bytes = oidmap.slot_value(old_map, i)- val mapped = refmap.get(mappings, value)- if mapped is some new_value {- oidmap.put(out, key, new_value)- } else {- oidmap.put(out, key, value)- }- }- i++- }- return out-}--fn free_maps(ctx: mut MatCtx) void = trust {- refmap.free(ctx.trees)- refmap.free(ctx.blobs)- refmap.free(ctx.commits)- refmap.free(ctx.conflicts)-}--pub fn run(repo: layout.Repo) i32 = trust {- val git_path = layout.git_dir(repo)- val git_opt = object.open(git_path)- val git_repo: mut object.GitRepo = @zeroed- val has_git: mut bool = false- match git_opt {- ok g => {- git_repo = g- has_git = true- }- err _ => {- files.free_path(git_path)- }- }-- 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 => {- oidmap.free(commits_map)- commits_map = m- }- err _ => {- maps_ok = false- }- }- match trees_map_opt {- ok m => {- oidmap.free(trees_map)- trees_map = m- }- err _ => {- maps_ok = false- }- }- match blobs_map_opt {- ok m => {- oidmap.free(blobs_map)- blobs_map = m- }- err _ => {- maps_ok = false- }- }- if !maps_ok {- msg.error_prefix()- stdio.eprint("corrupt git mapping table\n", {})- oidmap.free(commits_map)- oidmap.free(trees_map)- oidmap.free(blobs_map)- if has_git {- object.free(git_repo)- }- return 1- }-- 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", {})- oidmap.free(commits_map)- oidmap.free(trees_map)- oidmap.free(blobs_map)- if has_git {- object.free(git_repo)- }- return 1- }- }- val handles: list[ref store.Handle] = txn.handles(tx)- val ctx: mut MatCtx = MatCtx{- repo: repo,- tx: tx,- handles: handles,- git: git_repo,- has_git: has_git,- trees: refmap.new(64),- blobs: refmap.new(64),- commits: refmap.new(64),- conflicts: refmap.new(64),- raw_saves: lists.new[ref RawSave](),- new_commits: 0,- new_trees: 0,- new_blobs: 0,- changed: false- }-- val roots: list[objid.Id] = graph.roots(tx.view)- val ordered: list[objid.Id] = ordered_commits(handles, roots)- free_ids(roots)-- val failed: mut bool = false- for old_id in ordered {- val body_opt = state.read_body(handles, old_id, types.COMMIT)- val body: mut bytes.Bytes = bytes.empty()- match body_opt {- some b => {- body = b- }- none => {- failed = true- }- }- if failed {- break- }- val decoded = commit.decode(body)- val c: mut ref commit.Commit = @zeroed- match decoded {- ok v => {- c = v- }- err _ => {- failed = true- }- }- if failed {- files.free_buffer(body)- break- }- val new_root: objid.Id = materialize_node(ctx, c.root_tree, 1, 0)- if objid.Id.is_none(new_root) {- failed = true- commit.free_commit(c)- files.free_buffer(body)- break- }- val new_parents: mut list[objid.Id] = lists.new[objid.Id]()- val changed: mut bool = !objid.Id.eql(new_root, c.root_tree)- for p in c.parents {- val mapped = map_get(ctx.commits, p)- if mapped is some m {- @append(new_parents, m)- if !objid.Id.eql(m, p) {- changed = true- }- } else {- failed = true- break- }- }- if failed {- @listfree(new_parents)- commit.free_commit(c)- files.free_buffer(body)- break- }- if !changed {- map_put(ctx.commits, old_id, old_id)- @listfree(new_parents)- commit.free_commit(c)- files.free_buffer(body)- continue- }- @listfree(c.parents)- c.parents = new_parents- c.root_tree = new_root- val new_body: bytes.Bytes = commit.encode(c)- val new_id: objid.Id = txn.add_object(tx, types.COMMIT, new_body)- map_put(ctx.commits, old_id, new_id)- ctx.new_commits++- ctx.changed = true- record_raw(ctx, old_id, new_id)- commit.free_commit(c)- files.free_buffer(body)- }-- if failed {- msg.error_prefix()- stdio.eprint("git materialize failed (missing or corrupt object)\n", {})- free_ids(ordered)- free_raw_saves(ctx.raw_saves)- free_maps(ctx)- txn.abort(tx)- oidmap.free(commits_map)- oidmap.free(trees_map)- oidmap.free(blobs_map)- if has_git {- object.free(git_repo)- }- return 1- }-- if !ctx.changed {- msg.info_prefix()- stdio.print("already materialized\n", {})- free_ids(ordered)- free_raw_saves(ctx.raw_saves)- free_maps(ctx)- txn.abort(tx)- oidmap.free(commits_map)- oidmap.free(trees_map)- oidmap.free(blobs_map)- if has_git {- object.free(git_repo)- }- return 0- }-- val v: mut ref view.View = tx.view- val new_heads: mut list[objid.Id] = lists.new[objid.Id]()- for h in v.heads {- @append(new_heads, mapped_commit(ctx, h))- }- @listfree(v.heads)- v.heads = new_heads- val bi: mut usize = 0- for bi < @len(v.bookmarks) {- val bo = @get(v.bookmarks, bi)- if bo is some bm {- val i: mut usize = 0- for i < @len(bm.targets.adds) {- val o = @get(bm.targets.adds, i)- if o is some id {- @set(bm.targets.adds, i, mapped_commit(ctx, id))- }- i++- }- val j: mut usize = 0- for j < @len(bm.targets.removes) {- val o = @get(bm.targets.removes, j)- if o is some id {- @set(bm.targets.removes, j, mapped_commit(ctx, id))- }- j++- }- }- bi++- }- val ti: mut usize = 0- for ti < @len(v.tags) {- val to = @get(v.tags, ti)- if to is some t {- t.target = mapped_commit(ctx, t.target)- }- ti++- }- val ri: mut usize = 0- for ri < @len(v.remote_refs) {- val ro = @get(v.remote_refs, ri)- if ro is some rr {- rr.target = mapped_commit(ctx, rr.target)- }- ri++- }- val wi: mut usize = 0- for wi < @len(v.working_copies) {- val wo = @get(v.working_copies, wi)- if wo is some w {- w.target = mapped_commit(ctx, w.target)- }- wi++- }-- val status: i32 = txn.finish(tx, bytes.bytes(c"git materialize", 15))- if status != 0 {- free_ids(ordered)- free_raw_saves(ctx.raw_saves)- free_maps(ctx)- oidmap.free(commits_map)- oidmap.free(trees_map)- oidmap.free(blobs_map)- if has_git {- object.free(git_repo)- }- return status- }-- for rs in ctx.raw_saves {- val _ = gitmap.save_raw(repo, rs.id, rs.body)- }- free_raw_saves(ctx.raw_saves)-- val new_commits_map: oidmap.OidMap = remap_table(commits_map, ctx.commits)- oidmap.free(commits_map)- commits_map = new_commits_map- val new_trees_map: oidmap.OidMap = remap_table(trees_map, ctx.trees)- oidmap.free(trees_map)- trees_map = new_trees_map- val new_blobs_map: oidmap.OidMap = remap_table(blobs_map, ctx.blobs)- oidmap.free(blobs_map)- blobs_map = new_blobs_map- if !gitmap.save_map(repo, str.from_cstr(c"commits"), commits_map)- || !gitmap.save_map(repo, str.from_cstr(c"trees"), trees_map)- || !gitmap.save_map(repo, str.from_cstr(c"blobs"), blobs_map) {- msg.error_prefix()- stdio.eprint("failed to write git mapping tables\n", {})- }- checkout.clear_stat_cache(repo)- msg.info_prefix()- stdio.print(- "materialized {d} commits, {d} trees, {d} blobs\n",- {ctx.new_commits, ctx.new_trees, ctx.new_blobs}- )-- free_ids(ordered)- free_maps(ctx)- oidmap.free(commits_map)- oidmap.free(trees_map)- oidmap.free(blobs_map)- if has_git {- object.free(git_repo)- }- return 0-}--- a/veins/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/veins/src/git/object.sx+++ /dev/null@@ -1,1242 +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.--link "-lz"--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-}--/// Open the git mirror. On success the returned repository owns `git_dir`;-/// on error the caller retains ownership of `git_dir`.-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/veins/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/veins/src/git/refmap.sx+++ /dev/null@@ -1,165 +0,0 @@-/// Open-addressed map from 32-byte veins object IDs to 32-byte veins IDs.-///-/// Used while rewriting lazy git-backed objects into canonical stored objects.--val bytes = use("../core/bytes.sx")--pub val ID_LEN: usize = 32-pub val SLOT_LEN: usize = 65--pub type RefMap = {- 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 hash_id(id: bytes.Bytes) u64 = {- val h: mut u64 = 1469598103934665603- val i: mut usize = 0- for i < ID_LEN {- h = (h ^ (bytes.Bytes.at(id, i) as u64)) * 1099511628211- i++- }- return h-}--fn key_ptr(map: RefMap, i: usize) ref u8 = trust {- return @ptradd(map.slots, (i * SLOT_LEN + 1) as i64)-}--fn value_ptr(map: RefMap, i: usize) ref u8 = trust {- return @ptradd(map.slots, (i * SLOT_LEN + 1 + ID_LEN) as i64)-}--fn used_at(map: RefMap, i: usize) bool = trust {- return @load8(@ptradd(map.slots, (i * SLOT_LEN) as i64)) != 0-}--fn set_used(map: RefMap, i: usize) void = trust {- @store8(@ptradd(map.slots, (i * SLOT_LEN) as i64), 1)-}--fn slot_eql(map: RefMap, i: usize, key: bytes.Bytes) bool = trust {- return bytes.Bytes.eql(bytes.bytes(key_ptr(map, i), ID_LEN), key)-}--fn copy_key(map: RefMap, i: usize, key: bytes.Bytes) void = trust {- @memcpy(key_ptr(map, i) as ref void, key.ptr as ref void, ID_LEN)-}--fn copy_value(map: RefMap, i: usize, value: bytes.Bytes) void = trust {- @memcpy(value_ptr(map, i) as ref void, value.ptr as ref void, ID_LEN)-}--pub fn new(initial: usize) RefMap = 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 RefMap{slots: p, cap: cap, len: 0}-}--pub fn free(map: mut RefMap) void = trust {- if map.slots != none {- @free(map.slots as ref void)- }- map.slots = none- map.cap = 0- map.len = 0-}--fn insert_existing(- map: mut RefMap,- key: bytes.Bytes,- value: bytes.Bytes-) void = trust {- val mask: usize = map.cap - 1- val start: usize = (hash_id(key) as usize) & mask- val idx: mut usize = start- for {- if !used_at(map, idx) {- set_used(map, idx)- copy_key(map, idx, key)- copy_value(map, idx, value)- map.len++- return- }- if slot_eql(map, idx, key) {- copy_value(map, idx, value)- return- }- idx = (idx + 1) & mask- }-}--fn grow(map: mut RefMap) 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 key: bytes.Bytes = bytes.bytes(- @ptradd(old_slots, (i * SLOT_LEN + 1) as i64),- ID_LEN- )- val value: bytes.Bytes = bytes.bytes(- @ptradd(old_slots, (i * SLOT_LEN + 1 + ID_LEN) as i64),- ID_LEN- )- insert_existing(map, key, value)- }- i++- }- @free(old_slots as ref void)-}--/// Insert or replace `key` with `value`.-pub fn put(map: mut RefMap, key: bytes.Bytes, value: bytes.Bytes) void = trust {- pre {- key_len: key.len == ID_LEN- value_len: value.len == ID_LEN- }- if (map.len + 1) * 10 >= map.cap * 7 {- grow(map)- }- insert_existing(map, key, value)-}--/// The stored value for `key`, borrowed from the map.-pub fn get(map: RefMap, key: bytes.Bytes) option[bytes.Bytes] = trust {- pre {- key_len: key.len == ID_LEN- }- if map.cap == 0 {- return none- }- val mask: usize = map.cap - 1- val start: usize = (hash_id(key) as usize) & mask- val idx: mut usize = start- for {- if !used_at(map, idx) {- return none- }- if slot_eql(map, idx, key) {- return some bytes.bytes(value_ptr(map, idx), ID_LEN)- }- idx = (idx + 1) & mask- if idx == start {- return none- }- }- return none-}--- a/veins/src/git/refs.sx+++ /dev/null@@ -1,295 +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]- remotes: 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) {- if r.oid.ptr != none {- val old: mut ref void = r.oid.ptr as ref void- @free(old)- }- 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.from_cstr(child_rel.ptr), oid)- }- files.free_buffer(content)- }- }- 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 remotes: mut list[ref Ref] = lists.new[ref Ref]()- val remotes_base: str.StringView = files.join(git_dir, str.from_cstr(c"refs/remotes"))- read_ref_dir(remotes_base, str.view(none, 0), remotes)- files.free_path(remotes_base)- val head: bytes.Bytes = resolve_head(git_dir, branches, tags)- return RefSet{branches: branches, tags: tags, remotes: remotes, 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)- free_refs(set.remotes)- if set.head.ptr != none {- val hp: mut ref void = set.head.ptr as ref void- @free(hp)- }-}--- a/veins/src/git/remote.sx+++ /dev/null@@ -1,248 +0,0 @@-/// Git bridge remotes: fetch and push through the `.veins/git` mirror.--val stdio = use("std/stdio")-val str = use("std/string")-val os = use("std/os")-val bytes = use("../core/bytes.sx")-val buf = use("../core/buf.sx")-val lists = use("../core/lists.sx")-val layout = use("../store/layout.sx")-val files = use("../io/files.sx")-val config = use("../core/repoconfig.sx")-val import = use("import.sx")-val export = use("export.sx")-val stream = use("../net/stream.sx")-val cmsg = use("../core/msg.sx")--pub fn key_for(remote: bytes.Bytes, field: bytes.Bytes) bytes.Bytes = trust {- val prefix: bytes.Bytes = bytes.bytes(c"remote.", 7)- val out: ref u8 = @alloc(prefix.len + remote.len + 1 + field.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, remote.ptr as ref void, remote.len)- @store8(@ptradd(out, (prefix.len + remote.len) as i64), 46)- @memcpy(- @ptradd(out, (prefix.len + remote.len + 1) as i64) as ref void,- field.ptr as ref void,- field.len- )- return bytes.bytes(out, prefix.len + remote.len + 1 + field.len)-}--pub fn url_of(repo: layout.Repo, remote: bytes.Bytes) option[bytes.Bytes] = trust {- val k: bytes.Bytes = key_for(remote, bytes.bytes(c"url", 3))- val v = config.get(repo, k)- bytes.free_owned(k)- return v-}--pub fn key_name_of(repo: layout.Repo, remote: bytes.Bytes) option[bytes.Bytes] = trust {- val k: bytes.Bytes = key_for(remote, bytes.bytes(c"key", 3))- val v = config.get(repo, k)- bytes.free_owned(k)- return v-}--pub fn tls_pin_of(repo: layout.Repo, remote: bytes.Bytes) option[bytes.Bytes] = trust {- val k: bytes.Bytes = key_for(remote, bytes.bytes(c"tls-pin", 7))- val v = config.get(repo, k)- bytes.free_owned(k)- return v-}--fn git_command(repo: layout.Repo, args: list[bytes.Bytes]) bytes.Bytes = trust {- val out: mut buf.Buf = buf.new(128)- buf.Buf.put_raw(out, c"git" as ref u8, 3)- val gitdir: str.StringView = layout.git_dir(repo)- val gz: ref u8 = bytes.Bytes.to_cstr(bytes.bytes(gitdir.ptr, gitdir.len))- buf.Buf.put_raw(out, c" -C " as ref u8, 4)- val q: bytes.Bytes = stream.quote(bytes.from_cstr(gz))- buf.Buf.put_bytes(out, q)- bytes.free_owned(q)- @free(gz as ref void)- files.free_path(gitdir)- for a in args {- buf.Buf.put_u8(out, 32)- val qa: bytes.Bytes = stream.quote(a)- buf.Buf.put_bytes(out, qa)- bytes.free_owned(qa)- }- val r: bytes.Bytes = bytes.Bytes.dup(buf.Buf.view(out))- buf.Buf.free(out)- return r-}--fn run_git(repo: layout.Repo, args: list[bytes.Bytes]) i32 = trust {- val cmd: bytes.Bytes = git_command(repo, args)- val z: ref u8 = bytes.Bytes.to_cstr(cmd)- val code: i32 = os.run(z)- @free(z as ref void)- bytes.free_owned(cmd)- return code-}--/// Make sure the bare mirror exists and knows about `remote`.-pub fn configure_mirror(repo: layout.Repo, remote: bytes.Bytes, url: bytes.Bytes) bool = trust {- val gitdir: str.StringView = layout.git_dir(repo)- if !files.exists_dir(gitdir) {- files.free_path(gitdir)- return false- }- files.free_path(gitdir)- val args: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()- @append(args, bytes.Bytes.dup(bytes.bytes(c"remote", 6)))- @append(args, bytes.Bytes.dup(bytes.bytes(c"remove", 6)))- @append(args, bytes.Bytes.dup(remote))- run_git(repo, args)- free_args(args)- val add: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()- @append(add, bytes.Bytes.dup(bytes.bytes(c"remote", 6)))- @append(add, bytes.Bytes.dup(bytes.bytes(c"add", 3)))- @append(add, bytes.Bytes.dup(remote))- @append(add, bytes.Bytes.dup(url))- val code: i32 = run_git(repo, add)- free_args(add)- return code == 0-}--fn free_args(args: list[bytes.Bytes]) void = trust {- for a in args {- if a.ptr != none {- bytes.free_owned(a)- }- }- @listfree(args)-}--pub fn fetch(repo: layout.Repo, remote: bytes.Bytes) i32 = trust {- val url_opt = url_of(repo, remote)- if url_opt is none {- cmsg.error_prefix()- stdio.eprint("unknown remote: {s}\n", {str.view(remote.ptr, remote.len as i64)})- return 1- }- val url: mut bytes.Bytes = bytes.empty()- match url_opt {- some v => {- url = v- }- none => {- return 1- }- }- val configured: bool = configure_mirror(repo, remote, url)- bytes.free_owned(url)- if !configured {- cmsg.error_prefix()- stdio.eprint("cannot configure git mirror\n", {})- return 1- }- val args: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()- @append(args, bytes.Bytes.dup(bytes.bytes(c"fetch", 5)))- @append(args, bytes.Bytes.dup(bytes.bytes(c"--prune", 7)))- @append(args, bytes.Bytes.dup(remote))- val code: i32 = run_git(repo, args)- free_args(args)- if code != 0 {- cmsg.error_prefix()- stdio.eprint("git fetch failed\n", {})- return 1- }- return import.run(repo)-}--pub fn push(repo: layout.Repo, remote: bytes.Bytes, bookmark: bytes.Bytes) i32 = trust {- val url_opt = url_of(repo, remote)- if url_opt is none {- cmsg.error_prefix()- stdio.eprint("unknown remote: {s}\n", {str.view(remote.ptr, remote.len as i64)})- return 1- }- val url: mut bytes.Bytes = bytes.empty()- match url_opt {- some v => {- url = v- }- none => {- return 1- }- }- val configured: bool = configure_mirror(repo, remote, url)- bytes.free_owned(url)- if !configured {- cmsg.error_prefix()- stdio.eprint("cannot configure git mirror\n", {})- return 1- }- val ex: i32 = export.run(repo)- if ex != 0 {- return ex- }- val refspec: ref u8 = @fmtalloc(- "refs/heads/{s}:refs/heads/{s}",- {str.view(bookmark.ptr, bookmark.len as i64), str.view(bookmark.ptr, bookmark.len as i64)}- )- val args: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()- @append(args, bytes.Bytes.dup(bytes.bytes(c"push", 4)))- @append(args, bytes.Bytes.dup(remote))- @append(args, bytes.from_cstr(refspec))- val code: i32 = run_git(repo, args)- free_args(args)- if code != 0 {- cmsg.error_prefix()- stdio.eprint("git push failed\n", {})- return 1- }- stdio.print(- "pushed {s} to {s}\n",- {str.view(bookmark.ptr, bookmark.len as i64), str.view(remote.ptr, remote.len as i64)}- )- return 0-}--/// List configured remote names.-pub fn list_remotes(repo: layout.Repo) list[bytes.Bytes] = trust {- val out: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()- val p: str.StringView = layout.config_path(repo)- val data_opt = files.read_all(p)- files.free_path(p)- if data_opt is some d {- val start: mut usize = 0- val i: mut usize = 0- for i <= d.len {- if i == d.len || bytes.Bytes.at(d, i) == 10 {- val line: bytes.Bytes = bytes.Bytes.slice(d, start, i)- if find_sub(line, bytes.bytes(c"remote.", 7)) == 0 {- val dot: i64 = find_sub_from(line, bytes.bytes(c".url", 4), 7)- if dot > 7 {- @append(- out,- bytes.Bytes.dup(bytes.Bytes.slice(line, 7, dot as usize))- )- }- }- start = i + 1- }- i++- }- files.free_buffer(d)- }- return out-}--fn find_sub(hay: bytes.Bytes, needle: bytes.Bytes) i64 = trust {- return find_sub_from(hay, needle, 0)-}--fn find_sub_from(hay: bytes.Bytes, needle: bytes.Bytes, from: usize) i64 = trust {- if needle.len > hay.len {- return -1- }- val i: mut usize = from- for i <= hay.len - needle.len {- if bytes.Bytes.eql(bytes.Bytes.slice(hay, i, i + needle.len), needle) {- return i as i64- }- i++- }- return -1-}--- a/veins/src/io/files.sx+++ /dev/null@@ -1,227 +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 out: mut list[ref u8] = lists.new[ref u8]()- val z: str.ZString = trust str.zstr_from[allocators.HeapAllocator](heap(), p)- if z.ptr == none {- return out- }- val arena_r = trust allocators.ScopedArena.new(4096 as usize)- match arena_r {- ok sa => {- val la: allocators.ListArena = allocators.ListArena{arena: sa}- val names = trust fs.walk_dir_cstr[allocators.ListArena](la, z.ptr)- if names is some entries {- for n in entries {- @append(out, n)- }- }- trust allocators.ScopedArena.free(sa)- }- err _ => {- }- }- trust str.zstr_free[allocators.HeapAllocator](heap(), z)- return out-}--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/veins/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, ...) 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/veins/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/veins/src/main.sx+++ /dev/null@@ -1,1094 +0,0 @@-link "-lz"--val stdio = use("std/stdio")-val str = use("std/string")-val os = use("std/os")-val testing = use("std/testing")-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 remote_cmd = use("cli/remote_cmd.sx")-val clone_cmd = use("cli/clone_cmd.sx")-val fetch_cmd = use("cli/fetch_cmd.sx")-val push_cmd = use("cli/push_cmd.sx")-val serve_cmd = use("cli/serve_cmd.sx")-val key_cmd = use("cli/key_cmd.sx")-val auth_cmd = use("cli/auth_cmd.sx")-val access_cmd = use("cli/access_cmd.sx")-val whoami_cmd = use("cli/whoami_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 ls_cmd = use("cli/ls_cmd.sx")-val log_cmd = use("cli/log_cmd.sx")-val show_cmd = use("cli/show_cmd.sx")-val hash_cmd = use("cli/hash_cmd.sx")-val diff_cmd = use("cli/diff_cmd.sx")-val merge_cmd = use("cli/merge_cmd.sx")-val resolve_cmd = use("cli/resolve_cmd.sx")-val new_cmd = use("cli/new_cmd.sx")-val bookmark_cmd = use("cli/bookmark_cmd.sx")-val tag_cmd = use("cli/tag_cmd.sx")-val cfg_cmd = use("cli/cfg_cmd.sx")-val op_cmd = use("cli/op_cmd.sx")-val inf_cmd = use("cli/inf_cmd.sx")-val rm_cmd = use("cli/rm_cmd.sx")-val mv_cmd = use("cli/mv_cmd.sx")-val ex_cmd = use("cli/ex_cmd.sx")-val lists = use("core/lists.sx")-val layout = use("store/layout.sx")--extern (C) fn c_malloc(size: usize) ref void = "malloc"-extern (C) fn c_free(p: ref void) void = "free"--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 parse_count(b: bytes.Bytes, start: usize) option[usize] = trust {- if start >= b.len {- return none- }- val value: mut usize = 0- val i: mut usize = start- for i < b.len {- val c: u8 = bytes.Bytes.at(b, i)- if c < 48 || c > 57 {- return none- }- value = value * 10 + (c - 48) as usize- i++- }- if value == 0 {- return none- }- return some value-}--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_inf() i32 = trust {- val repo_opt = open_repo_or_error(str.from_cstr(c"."))- match repo_opt {- some repo => {- val status: i32 = inf_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 limit: mut usize = 0- val first: mut bool = false- 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)- 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 && (cmd_is(a, c"-l", 2) || cmd_is(a, c"-f", 2)) {- if i + 1 >= @len(args) {- msg.error_prefix()- stdio.eprint("{s} requires a count\n", {str.from_cstr(a)})- return 1- }- val v = @get(args, i + 1)- val n_opt: mut option[usize] = none- if v is some rv {- n_opt = parse_count(bytes.from_cstr(rv), 0)- }- if n_opt is some n {- limit = n- first = cmd_is(a, c"-f", 2)- i++- } else {- msg.error_prefix()- stdio.eprint("{s} requires a positive count\n", {str.from_cstr(a)})- return 1- }- } elif !end_flags && av.len > 2- && bytes.Bytes.at(av, 0) == 45- && (bytes.Bytes.at(av, 1) == 108 || bytes.Bytes.at(av, 1) == 102) {- val n_opt = parse_count(av, 2)- if n_opt is some n {- limit = n- first = bytes.Bytes.at(av, 1) == 102- } else {- msg.error_prefix()- stdio.eprint("invalid log count: {s}\n", {str.from_cstr(a)})- return 1- }- } elif !end_flags && av.len > 1- && (bytes.Bytes.at(av, 0) == 108 || bytes.Bytes.at(av, 0) == 102) {- val n_opt = parse_count(av, 1)- if n_opt is some n {- limit = n- first = bytes.Bytes.at(av, 0) == 102- } else {- rev = av- }- } elif !end_flags && is_flag(a) {- msg.error_prefix()- stdio.eprint("unknown flag: {s}\n", {str.from_cstr(a)})- return 1- } else {- rev = av- }- }- 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, limit, first)- layout.free_repo(repo)- return status- }- none => {- return 1- }- }-}--fn run_show(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 = show_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_merge(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 = merge_cmd.merge(repo, revs)- layout.free_repo(repo)- @listfree(revs)- return status- }- none => {- @listfree(revs)- return 1- }- }-}--fn run_rebase(args: list[ref u8], start: usize) i32 = trust {- val source: mut bytes.Bytes = bytes.empty()- val dest: mut bytes.Bytes = bytes.empty()- 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"-s", 2) || cmd_is(a, c"-source", 7)) {- if i + 1 < @len(args) {- val v = @get(args, i + 1)- if v is some rv {- source = 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"-d", 2) || cmd_is(a, c"-destination", 12)) {- if i + 1 < @len(args) {- val v = @get(args, i + 1)- if v is some rv {- dest = 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 && is_flag(a) {- msg.error_prefix()- stdio.eprint("unknown flag: {s}\n", {str.from_cstr(a)})- return 1- } else {- msg.error_prefix()- stdio.eprint("unexpected argument: {s}\n", {str.from_cstr(a)})- return 1- }- }- i++- }- if source.len == 0 || dest.len == 0 {- msg.error_prefix()- stdio.eprint("rebase requires -s <rev> and -d <rev>\n", {})- return 1- }- val repo_opt = open_repo_or_error(str.from_cstr(c"."))- match repo_opt {- some repo => {- val status: i32 = merge_cmd.rebase(repo, source, dest)- layout.free_repo(repo)- return status- }- none => {- return 1- }- }-}--fn run_xs(args: list[ref u8], start: usize) i32 = trust {- val porcelain: 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"-porcelain", 10) || cmd_is(a, c"-p", 2)) {- porcelain = true- } elif !end_flags && is_flag(a) {- msg.error_prefix()- stdio.eprint("unknown flag: {s}\n", {str.from_cstr(a)})- return 1- } else {- msg.error_prefix()- stdio.eprint("unexpected argument: {s}\n", {str.from_cstr(a)})- return 1- }- }- i++- }- val repo_opt = open_repo_or_error(str.from_cstr(c"."))- match repo_opt {- some repo => {- val status: i32 = resolve_cmd.xs(repo, porcelain)- layout.free_repo(repo)- return status- }- none => {- return 1- }- }-}--fn run_resolve(args: list[ref u8], start: usize) i32 = trust {- val take: mut bytes.Bytes = bytes.empty()- val tool: mut bytes.Bytes = bytes.empty()- val list_only: mut bool = false- val paths: 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"-list", 5) || cmd_is(a, c"-l", 2)) {- list_only = true- } elif !end_flags && (cmd_is(a, c"-take", 5) || cmd_is(a, c"-t", 2)) {- if i + 1 < @len(args) {- val v = @get(args, i + 1)- if v is some rv {- take = bytes.from_cstr(rv)- i++- }- } else {- msg.error_prefix()- stdio.eprint("{s} requires ours, theirs, or base\n", {str.from_cstr(a)})- @listfree(paths)- return 1- }- } elif !end_flags && cmd_is(a, c"-tool", 5) {- if i + 1 < @len(args) {- val v = @get(args, i + 1)- if v is some rv {- tool = bytes.from_cstr(rv)- i++- }- } else {- msg.error_prefix()- stdio.eprint("{s} requires a command\n", {str.from_cstr(a)})- @listfree(paths)- return 1- }- } elif !end_flags && is_flag(a) {- msg.error_prefix()- stdio.eprint("unknown flag: {s}\n", {str.from_cstr(a)})- @listfree(paths)- return 1- } else {- @append(paths, bytes.from_cstr(a))- }- }- i++- }- val repo_opt = open_repo_or_error(str.from_cstr(c"."))- match repo_opt {- some repo => {- val status: mut i32 = 1- if list_only {- status = resolve_cmd.xs(repo, false)- } elif @len(paths) == 0 {- msg.error_prefix()- stdio.eprint("resolve requires at least one path\n", {})- } else {- status = resolve_cmd.resolve(repo, take, tool, paths)- }- layout.free_repo(repo)- @listfree(paths)- return status- }- none => {- @listfree(paths)- return 1- }- }-}--fn run_mv(args: list[ref u8], start: usize) i32 = trust {- val paths: 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(paths)- return 1- } else {- @append(paths, bytes.from_cstr(a))- }- }- i++- }- val repo_opt = open_repo_or_error(str.from_cstr(c"."))- match repo_opt {- some repo => {- val status: i32 = mv_cmd.run(repo, paths)- layout.free_repo(repo)- @listfree(paths)- return status- }- none => {- @listfree(paths)- 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 message_is_blank(parts: list[bytes.Bytes]) bool = trust {- for p in parts {- val i: mut usize = 0- for i < p.len {- val c: u8 = bytes.Bytes.at(p, i)- if c != 32 && c != 9 && c != 10 && c != 13 {- return false- }- i++- }- }- return true-}--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- }- }- if message_is_blank(parts) {- msg.error_prefix()- stdio.eprint("commit requires a non-empty message (-message)\n", {})- @listfree(parts)- return 1- }- 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_amend(args: list[ref u8], start: usize) i32 = trust {- val rev: mut bytes.Bytes = bytes.empty()- 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 1- }- } elif !end_flags && is_flag(a) {- msg.error_prefix()- stdio.eprint("unknown flag: {s}\n", {str.from_cstr(a)})- @listfree(parts)- return 1- } elif rev.len == 0 {- rev = bytes.from_cstr(a)- } else {- @append(parts, bytes.from_cstr(a))- }- }- i++- }- if rev.len == 0 {- msg.error_prefix()- stdio.eprint("amend requires a revision\n", {})- @listfree(parts)- return 1- }- if message_is_blank(parts) {- msg.error_prefix()- stdio.eprint("amend requires a non-empty message (-message)\n", {})- @listfree(parts)- return 1- }- val repo_opt = open_repo_or_error(str.from_cstr(c"."))- match repo_opt {- some repo => {- val status: i32 = new_cmd.amend(repo, rev, parts)- @listfree(parts)- layout.free_repo(repo)- return status- }- 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-}--fn leak_report() void = trust {- val capacity: usize = 262144- val copy: ref u8 = c_malloc(capacity) as ref u8- val d = @dumpmemleaks()- stdio.print(- "leak-check: enabled={d} live_allocations={d} live_bytes={d} allocations={d} frees={d} peak_bytes={d} invalid_frees={d}\n",- {- d.enabled,- d.live_allocations,- d.live_bytes,- d.total_allocations,- d.total_frees,- d.peak_live_bytes,- d.invalid_frees- }- )- val max_records: i64 = (capacity / (@sizeof(testing.LeakRecord) as usize)) as i64- val count: i64 = d.record_count- val to_copy: mut i64 = count- if to_copy > max_records {- to_copy = max_records- }- if to_copy > 0 && d.records != none {- @memcpy(- copy as ref void,- d.records as ref void,- (to_copy * (@sizeof(testing.LeakRecord) as i64)) as usize- )- }- val i: mut i64 = 0- for i < to_copy {- val rec = @ptradd(- copy,- (i * (@sizeof(testing.LeakRecord) as i64))- ) as ref testing.LeakRecord- stdio.print(- "leak-check: {d} bytes at {s}:{d} ({p})\n",- {rec.size, rec.file, rec.line, rec.address}- )- i++- }- c_free(copy as ref void)-}--fn leak_report_requested() bool = trust {- val v = os.env(c"VEINS_LEAK_REPORT")- match v {- some _ => {- return true- }- none => {- return false- }- }-}--fn run_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"remote", 6) {- return remote_cmd.run(args, 2)- }- if cmd_is(cmd, c"clone", 5) {- return clone_cmd.run(args, 2)- }- if cmd_is(cmd, c"fetch", 5) {- return fetch_cmd.run(args, 2)- }- if cmd_is(cmd, c"push", 4) {- return push_cmd.run(args, 2)- }- if cmd_is(cmd, c"serve", 5) {- return serve_cmd.run(args, 2)- }- if cmd_is(cmd, c"key", 3) {- return key_cmd.run(args, 2)- }- if cmd_is(cmd, c"auth", 4) {- return auth_cmd.run(args, 2)- }- if cmd_is(cmd, c"access", 6) {- return access_cmd.run(args, 2)- }- if cmd_is(cmd, c"whoami", 6) {- return whoami_cmd.run(args, 2)- }- if cmd_is(cmd, c"co", 2) || cmd_is(cmd, c"checkout", 8) {- return checkout_cmd.run(args, 2)- }- if cmd_is(cmd, c"stat", 4) || cmd_is(cmd, c"status", 6) {- return run_status()- }- if cmd_is(cmd, c"ls", 2) {- return ls_cmd.run(args, 2)- }- if cmd_is(cmd, c"inf", 3) {- return run_inf()- }- if cmd_is(cmd, c"log", 3) {- return run_log(args, 2)- }- if cmd_is(cmd, c"hash", 4) {- return hash_cmd.run(args, 2)- }- if cmd_is(cmd, c"show", 4) {- return run_show(args, 2)- }- if cmd_is(cmd, c"diff", 4) {- return run_diff(args, 2)- }- if cmd_is(cmd, c"merge", 5) {- return run_merge(args, 2)- }- if cmd_is(cmd, c"rebase", 6) {- return run_rebase(args, 2)- }- if cmd_is(cmd, c"xs", 2) {- return run_xs(args, 2)- }- if cmd_is(cmd, c"resolve", 7) {- return run_resolve(args, 2)- }- if cmd_is(cmd, c"new", 3) {- return run_new(args, 2)- }- if cmd_is(cmd, c"rm", 2) {- return rm_cmd.run(args, 2)- }- if cmd_is(cmd, c"mv", 2) {- return run_mv(args, 2)- }- if cmd_is(cmd, c"bmk", 3) {- return bookmark_cmd.run(args, 2)- }- if cmd_is(cmd, c"tag", 3) {- return tag_cmd.run(args, 2)- }- if cmd_is(cmd, c"cfg", 3) || cmd_is(cmd, c"config", 6) {- return cfg_cmd.run(args, 2)- }- if cmd_is(cmd, c"ex", 2) {- return ex_cmd.run(args, 2)- }- if cmd_is(cmd, c"desc", 4) || cmd_is(cmd, c"describe", 8) {- return run_describe(args, 2)- }- if cmd_is(cmd, c"go", 2) || cmd_is(cmd, c"commit", 6) {- return run_commit(args, 2)- }- if cmd_is(cmd, c"amend", 5) {- return run_amend(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("veins v0.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-}--pub fn main() i32 = trust {- val requested: bool = leak_report_requested()- val status: i32 = run_main()- if requested {- leak_report()- }- return status-}--- a/veins/src/merge/algebra.sx+++ /dev/null@@ -1,263 +0,0 @@-/// Conflict algebra: flattening, cancellation, and resolution of signed terms.-///-/// A sum is represented as an `adds` list of `n+1` terms and a `removes` list-/// of `n` terms. `simplify` consumes its inputs and returns a simplified sum.--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 conflict = use("../object/conflict.sx")-val tree = use("../object/tree.sx")-val state = use("../store/state.sx")-val store = use("../store/store.sx")-val files = use("../io/files.sx")-val txnmod = use("../store/txn.sx")--pub type Sum = {- adds: mut list[ref conflict.ConflictValue]- removes: mut list[ref conflict.ConflictValue]-}--pub fn empty() Sum = {- return Sum{- adds: lists.new[ref conflict.ConflictValue](),- removes: lists.new[ref conflict.ConflictValue]()- }-}--pub fn free_value(v: ref conflict.ConflictValue) void = trust {- @free(v as ref void)-}--pub fn free_values(xs: list[ref conflict.ConflictValue]) void = trust {- for v in xs {- free_value(v)- }- @listfree(xs)-}--pub fn free_sum(s: Sum) void = trust {- free_values(s.adds)- free_values(s.removes)-}--pub fn sum_is_unresolved(s: Sum) bool = {- if @len(s.removes) == 0 {- return false- }- if @len(s.adds) <= 1 {- return false- }- val first = @get(s.adds, 0)- if first is some f {- for x in s.adds {- if !conflict.ConflictValue.eql(f, x) {- return true- }- }- }- return false-}--/// The resolved value when the sum has one distinct add. Borrows the term.-pub fn resolved(s: Sum) option[ref conflict.ConflictValue] = {- if @len(s.adds) == 0 {- return none- }- val first = @get(s.adds, 0)- if first is some f {- for x in s.adds {- if !conflict.ConflictValue.eql(f, x) {- return none- }- }- return some f- }- return none-}--fn load_conflict(- handles: list[ref store.Handle],- id: objid.Id,- use_cache: bool,- tx: ref txnmod.Txn-) option[ref conflict.Conflict] = trust {- val body: mut bytes.Bytes = bytes.empty()- if use_cache {- val cached = txnmod.find_cached(tx, types.CONFLICT, id)- if cached is some cb {- body = bytes.Bytes.dup(cb)- }- }- if body.ptr == none {- val body_opt = state.read_body(handles, id, types.CONFLICT)- match body_opt {- some b => {- body = b- }- none => {- return none- }- }- }- val decoded = conflict.decode(body)- val out: mut option[ref conflict.Conflict] = none- match decoded {- ok c => {- out = some c- }- err _ => {- }- }- if out is none {- files.free_buffer(body)- }- return out-}--fn flatten_into(- handles: list[ref store.Handle],- vals: list[ref conflict.ConflictValue],- positive: bool,- adds: mut list[ref conflict.ConflictValue],- removes: mut list[ref conflict.ConflictValue],- depth: usize,- use_cache: bool,- tx: ref txnmod.Txn-) void = trust {- for v in vals {- if v.kind == tree.KIND_CONFLICT && depth < 64 {- val c_opt = load_conflict(handles, v.target, use_cache, tx)- if c_opt is some c {- flatten_into(handles, c.adds, positive, adds, removes, depth + 1, use_cache, tx)- flatten_into(handles, c.removes, !positive, adds, removes, depth + 1, use_cache, tx)- // The child lists were consumed by flatten_into; only the- // conflict struct itself remains owned here.- @free(c as ref void)- free_value(v)- continue- }- }- if positive {- @append(adds, v)- } else {- @append(removes, v)- }- }- @listfree(vals)-}--fn find_cancel(- adds: list[ref conflict.ConflictValue],- used: ref u8,- v: ref conflict.ConflictValue-) i32 = trust {- val i: mut usize = 0- for i < @len(adds) {- val used_flag: u8 = @load8(@ptradd(used, i as i64))- if used_flag == 0 {- val a = @get(adds, i)- if a is some av {- if conflict.ConflictValue.eql(av, v) {- return i as i32- }- }- }- i++- }- return -1-}--fn used_at(used: ref u8, i: usize) bool = trust {- return @load8(@ptradd(used, i as i64)) != 0-}--fn set_used(used: ref u8, i: usize) void = trust {- @store8(@ptradd(used, i as i64), 1)-}--/// Flatten, cancel, and compact. The input lists and terms are consumed.-fn simplify_inner(- handles: list[ref store.Handle],- adds_in: list[ref conflict.ConflictValue],- removes_in: list[ref conflict.ConflictValue],- use_cache: bool,- tx: ref txnmod.Txn-) Sum = trust {- val flat: mut Sum = empty()- flatten_into(handles, adds_in, true, flat.adds, flat.removes, 0, use_cache, tx)- flatten_into(handles, removes_in, false, flat.adds, flat.removes, 0, use_cache, tx)-- val n_adds: usize = @len(flat.adds)- val used: ref u8 = @alloc(n_adds + 1) as ref u8- @memset(used as ref void, 0, n_adds + 1)- val rem_used: ref u8 = @alloc(@len(flat.removes) + 1) as ref u8- @memset(rem_used as ref void, 0, @len(flat.removes) + 1)-- val r: mut usize = 0- for r < @len(flat.removes) {- val rv = @get(flat.removes, r)- if rv is some value {- val idx: i32 = find_cancel(flat.adds, used, value)- if idx >= 0 {- set_used(used, idx as usize)- @store8(@ptradd(rem_used, r as i64), 1)- }- }- r++- }-- val out: mut Sum = empty()- val a: mut usize = 0- for a < @len(flat.adds) {- val av = @get(flat.adds, a)- if av is some value {- if used_at(used, a) {- free_value(value)- } else {- @append(out.adds, value)- }- }- a++- }- val rr: mut usize = 0- for rr < @len(flat.removes) {- val rv = @get(flat.removes, rr)- if rv is some value {- if used_at(rem_used, rr) {- free_value(value)- } else {- @append(out.removes, value)- }- }- rr++- }- @free(used as ref void)- @free(rem_used as ref void)- @listfree(flat.adds)- @listfree(flat.removes)- return out-}--pub fn simplify(- handles: list[ref store.Handle],- adds_in: list[ref conflict.ConflictValue],- removes_in: list[ref conflict.ConflictValue]-) Sum = trust {- return simplify_inner(handles, adds_in, removes_in, false, none)-}--pub fn simplify_tx(- handles: list[ref store.Handle],- adds_in: list[ref conflict.ConflictValue],- removes_in: list[ref conflict.ConflictValue],- tx: ref txnmod.Txn-) Sum = trust {- return simplify_inner(handles, adds_in, removes_in, true, tx)-}--/// Encode a simplified, unresolved sum as a conflict object body.-pub fn conflict_body(s: Sum) bytes.Bytes = {- return conflict.encode(s.adds, s.removes)-}--- a/veins/src/merge/attributes.sx+++ /dev/null@@ -1,158 +0,0 @@-/// Tracked `.veinsattributes` rules that affect merging.-///-/// Rules are one per line: `glob attr=value ...`. Later matching rules override-/// earlier ones. Only `merge=text|binary` is interpreted here; other attributes-/// are accepted and ignored.--val str = use("std/string")-val bytes = use("../core/bytes.sx")-val ignore = use("../worktree/ignore.sx")-val files = use("../io/files.sx")-val layout = use("../store/layout.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 token_at(b: bytes.Bytes, start: usize) bytes.Bytes = trust {- val i: mut usize = start- for i < b.len {- val c: u8 = bytes.Bytes.at(b, i)- if c == 32 || c == 9 {- break- }- i++- }- return bytes.Bytes.slice(b, start, i)-}--fn skip_ws(b: bytes.Bytes, start: usize) usize = trust {- val i: mut usize = start- for i < b.len {- val c: u8 = bytes.Bytes.at(b, i)- if c != 32 && c != 9 {- break- }- i++- }- return i-}--fn has_slash(b: bytes.Bytes) bool = trust {- val i: mut usize = 0- for i < b.len {- if bytes.Bytes.at(b, i) == 47 {- return true- }- i++- }- return false-}--fn basename(b: bytes.Bytes) bytes.Bytes = trust {- val i: mut usize = b.len- for i > 0 {- if bytes.Bytes.at(b, i - 1) == 47 {- return bytes.Bytes.slice(b, i, b.len)- }- i--- }- return b-}--fn matches(pattern: bytes.Bytes, path: bytes.Bytes) bool = trust {- if ignore.glob_match(pattern, path) {- return true- }- if !has_slash(pattern) {- return ignore.glob_match(pattern, basename(path))- }- return false-}--fn value_is(v: bytes.Bytes, text: ref u8, len: usize) bool = trust {- return bytes.Bytes.eql(v, bytes.bytes(text, len))-}--/// True when the path's effective `merge` attribute is `binary`.-pub fn merge_binary(repo: layout.Repo, path: bytes.Bytes) bool = trust {- val root: str.StringView = layout.root_view(repo)- val p: str.StringView = files.join(root, str.from_cstr(c".veinsattributes"))- val data_opt = files.read_all(p)- files.free_path(p)- val data: mut bytes.Bytes = bytes.empty()- match data_opt {- some d => {- data = d- }- none => {- return false- }- }- val result: mut bool = false- 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 glob: bytes.Bytes = token_at(line, 0)- if glob.len > 0 && matches(glob, path) {- val t: mut usize = skip_ws(line, glob.len)- for t < line.len {- val tok_start: usize = t- val tok: bytes.Bytes = token_at(line, tok_start)- if tok.len == 0 {- break- }- val eq: mut i64 = -1- val k: mut usize = 0- for k < tok.len {- if bytes.Bytes.at(tok, k) == 61 && eq < 0 {- eq = k as i64- }- k++- }- if eq >= 0 {- val key: bytes.Bytes = bytes.Bytes.slice(tok, 0, eq as usize)- val valb: bytes.Bytes = bytes.Bytes.slice(- tok,- eq as usize + 1,- tok.len- )- if value_is(key, c"merge", 5) {- if value_is(valb, c"binary", 6) {- result = true- } elif value_is(valb, c"text", 4) {- result = false- }- }- }- t = skip_ws(line, tok_start + tok.len)- }- }- }- start = pos + 1- }- pos++- }- files.free_buffer(data)- return result-}--- a/veins/src/merge/engine.sx+++ /dev/null@@ -1,486 +0,0 @@-/// Merge-base selection and helpers that turn commit-level merges into the-/// signed tree terms consumed by `treemerge`.--val lists = use("../core/lists.sx")-val objid = use("../object/id.sx")-val graph = use("../object/graph.sx")-val store = use("../store/store.sx")-val txnmod = use("../store/txn.sx")-val layout = use("../store/layout.sx")-val object = use("../git/object.sx")-val rename = use("rename.sx")-val treemerge = use("treemerge.sx")--pub 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-}--pub fn parents_of(handles: list[ref store.Handle], id: objid.Id) list[objid.Id] = trust {- val out: mut list[objid.Id] = lists.new[objid.Id]()- val lc_opt = graph.load_commit(handles, id)- if lc_opt is some lc {- for p in lc.c.parents {- @append(out, graph.copy_id(p))- }- graph.free_loaded(lc)- }- return 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-}--pub fn single(id: objid.Id) list[objid.Id] = trust {- val xs: mut list[objid.Id] = lists.new[objid.Id]()- @append(xs, graph.copy_id(id))- return xs-}--/// Common ancestors that are not ancestors of another common ancestor.-pub fn merge_bases(- handles: list[ref store.Handle],- a: objid.Id,- b: objid.Id-) list[objid.Id] = trust {- val aa: list[objid.Id] = graph.collect(handles, single(a))- val bb: list[objid.Id] = graph.collect(handles, single(b))- val common: mut list[objid.Id] = lists.new[objid.Id]()- for x in aa {- if contains(bb, x) {- @append(common, graph.copy_id(x))- }- }- val out: mut list[objid.Id] = lists.new[objid.Id]()- for c in common {- val dominated: mut bool = false- for d in common {- if !objid.Id.eql(c, d) {- val desc: list[objid.Id] = graph.collect(handles, single(c))- if contains(desc, d) {- dominated = true- }- graph.free_ids(desc)- if dominated {- break- }- }- }- if !dominated {- @append(out, graph.copy_id(c))- }- }- graph.free_ids(aa)- graph.free_ids(bb)- graph.free_ids(common)- return out-}--pub fn is_ancestor(- handles: list[ref store.Handle],- ancestor: objid.Id,- descendant: objid.Id-) bool = trust {- if objid.Id.eql(ancestor, descendant) {- return true- }- val ids: list[objid.Id] = graph.collect(handles, single(descendant))- val found: bool = contains(ids, ancestor)- graph.free_ids(ids)- return found-}--fn graph_single(id: objid.Id) list[objid.Id] = trust {- val xs: mut list[objid.Id] = lists.new[objid.Id]()- @append(xs, id)- return xs-}--fn new_term(positive: bool, present: bool, id: objid.Id) ref treemerge.TreeTerm = trust {- val t: mut ref treemerge.TreeTerm = @alloc(@sizeof(treemerge.TreeTerm)) as ref treemerge.TreeTerm- t.positive = positive- t.present = present- t.id = graph.copy_id(id)- return t-}--fn free_terms(ts: list[ref treemerge.TreeTerm]) void = trust {- for t in ts {- val tp: mut ref void = t.id.ptr as ref void- @free(tp)- val ep: mut ref void = t as ref void- @free(ep)- }- @listfree(ts)-}--fn free_maps(ms: list[ref rename.RenameMap]) void = trust {- for m in ms {- if m is some mm {- if mm != none {- rename.free_map(mm)- @free(mm as ref void)- }- }- }- @listfree(ms)-}--fn empty_map() ref rename.RenameMap = trust {- val m: rename.RenameMap = rename.empty()- val out: mut ref rename.RenameMap = @alloc(@sizeof(rename.RenameMap)) as ref rename.RenameMap- out.entries = m.entries- return out-}--fn new_map(- handles: list[ref store.Handle],- git: ref object.GitRepo,- has_git: bool,- base: objid.Id,- side: objid.Id-) ref rename.RenameMap = trust {- val m: rename.RenameMap = rename.map_from(handles, git, has_git, base, side)- val out: mut ref rename.RenameMap = @alloc(@sizeof(rename.RenameMap)) as ref rename.RenameMap- out.entries = m.entries- return out-}--fn base_tree(- repo: layout.Repo,- tx: mut ref txnmod.Txn,- handles: list[ref store.Handle],- git: ref object.GitRepo,- has_git: bool,- bases: list[objid.Id],- adjacent_merge: bool-) option[objid.Id] = trust {- if @len(bases) == 0 {- return none- }- if @len(bases) == 1 {- val o = @get(bases, 0)- if o is some b {- return tree_of(handles, b)- }- return none- }- // Criss-cross: fold a virtual base from the first two commits. Deeper- // histories use the first LCA, which is conservative and deterministic.- val b0 = @get(bases, 0)- val b1 = @get(bases, 1)- if b0 is some first {- if b1 is some second {- val t0 = tree_of(handles, first)- val t1 = tree_of(handles, second)- val lcas: list[objid.Id] = merge_bases(handles, first, second)- val terms: mut list[ref treemerge.TreeTerm] = lists.new[ref treemerge.TreeTerm]()- val maps: mut list[ref rename.RenameMap] = lists.new[ref rename.RenameMap]()- @append(terms, new_term(true, has_opt(t0), option_id(t0)))- @append(terms, new_term(true, has_opt(t1), option_id(t1)))- @append(maps, empty_map())- @append(maps, empty_map())- if @len(lcas) > 0 {- val l0 = @get(lcas, 0)- if l0 is some lc {- val lt = tree_of(handles, lc)- @append(terms, new_term(false, has_opt(lt), option_id(lt)))- @append(maps, empty_map())- free_opt(lt)- }- } else {- @append(terms, new_term(false, false, objid.id(none)))- @append(maps, empty_map())- }- val out = treemerge.merge(- repo,- tx,- handles,- git,- has_git,- terms,- maps,- adjacent_merge- )- free_terms(terms)- free_maps(maps)- graph.free_ids(lcas)- free_opt(t0)- free_opt(t1)- return some out.tree- }- }- return none-}--fn option_id(o: option[objid.Id]) objid.Id = trust {- if o is some id {- return id- }- return objid.id(none)-}--fn has_opt(o: option[objid.Id]) bool = trust {- if o is some _ {- return true- }- return false-}--fn free_opt(o: option[objid.Id]) void = trust {- if o is some id {- @free(id.ptr as ref void)- }-}--/// Merge two commit ids, writing objects through `tx`.-pub fn merge_two(- repo: layout.Repo,- tx: mut ref txnmod.Txn,- handles: list[ref store.Handle],- git: ref object.GitRepo,- has_git: bool,- a: objid.Id,- b: objid.Id,- adjacent_merge: bool-) treemerge.Outcome = trust {- val ta = tree_of(handles, a)- val tb = tree_of(handles, b)- val bases: list[objid.Id] = merge_bases(handles, a, b)- val bt: option[objid.Id] = base_tree(repo, tx, handles, git, has_git, bases, adjacent_merge)- val terms: mut list[ref treemerge.TreeTerm] = lists.new[ref treemerge.TreeTerm]()- @append(terms, new_term(true, has_opt(ta), option_id(ta)))- @append(terms, new_term(true, has_opt(tb), option_id(tb)))- val maps: mut list[ref rename.RenameMap] = lists.new[ref rename.RenameMap]()- val base_id: mut objid.Id = objid.id(none)- if @len(bases) > 0 {- val o = @get(bases, 0)- if o is some first {- base_id = first- }- }- if objid.Id.is_none(base_id) {- @append(maps, empty_map())- @append(maps, empty_map())- } else {- @append(maps, new_map(handles, git, has_git, base_id, a))- @append(maps, new_map(handles, git, has_git, base_id, b))- }- if bt is some btree {- @append(terms, new_term(false, true, btree))- } else {- @append(terms, new_term(false, false, objid.id(none)))- }- @append(maps, empty_map())- val out = treemerge.merge(- repo,- tx,- handles,- git,- has_git,- terms,- maps,- adjacent_merge- )- free_terms(terms)- free_maps(maps)- graph.free_ids(bases)- free_opt(ta)- free_opt(tb)- free_opt(bt)- return out-}--/// Merge more than two heads by accumulating `S + R_i - B_i` terms.-pub fn merge_many(- repo: layout.Repo,- tx: mut ref txnmod.Txn,- handles: list[ref store.Handle],- git: ref object.GitRepo,- has_git: bool,- heads: list[objid.Id],- adjacent_merge: bool-) treemerge.Outcome = trust {- if @len(heads) == 1 {- val o = @get(heads, 0)- val t: mut option[objid.Id] = none- if o is some id {- t = tree_of(handles, id)- }- val terms: mut list[ref treemerge.TreeTerm] = lists.new[ref treemerge.TreeTerm]()- @append(terms, new_term(true, has_opt(t), option_id(t)))- val maps: mut list[ref rename.RenameMap] = lists.new[ref rename.RenameMap]()- @append(maps, empty_map())- val out = treemerge.merge(- repo,- tx,- handles,- git,- has_git,- terms,- maps,- adjacent_merge- )- free_terms(terms)- free_maps(maps)- free_opt(t)- return out- }- val terms: mut list[ref treemerge.TreeTerm] = lists.new[ref treemerge.TreeTerm]()- val maps: mut list[ref rename.RenameMap] = lists.new[ref rename.RenameMap]()- val first = @get(heads, 0)- val first_id: mut objid.Id = objid.id(none)- if first is some f {- first_id = f- }- val map_base: mut objid.Id = objid.id(none)- if @len(heads) > 1 {- val second = @get(heads, 1)- if second is some sh {- val bs: list[objid.Id] = merge_bases(handles, first_id, sh)- if @len(bs) > 0 {- val b0 = @get(bs, 0)- if b0 is some bid {- map_base = graph.copy_id(bid)- }- }- graph.free_ids(bs)- }- }- for h in heads {- val t = tree_of(handles, h)- @append(terms, new_term(true, has_opt(t), option_id(t)))- if objid.Id.is_none(map_base) {- @append(maps, empty_map())- } else {- @append(maps, new_map(handles, git, has_git, map_base, h))- }- free_opt(t)- }- val hi: mut usize = 1- for hi < @len(heads) {- val o = @get(heads, hi)- if o is some h {- val bases: list[objid.Id] = merge_bases(handles, first_id, h)- val bt = base_tree(repo, tx, handles, git, has_git, bases, adjacent_merge)- if bt is some btree {- @append(terms, new_term(false, true, btree))- } else {- @append(terms, new_term(false, false, objid.id(none)))- }- @append(maps, empty_map())- graph.free_ids(bases)- free_opt(bt)- }- hi++- }- val out = treemerge.merge(- repo,- tx,- handles,- git,- has_git,- terms,- maps,- adjacent_merge- )- free_terms(terms)- free_maps(maps)- if map_base.ptr != none {- graph.free_ids(graph_single(map_base))- }- return out-}--/// Compute a rebased tree: `tree(C) + Σ(tree(P'_i) - tree(P_i))`.-pub fn rewrite_tree(- repo: layout.Repo,- tx: mut ref txnmod.Txn,- handles: list[ref store.Handle],- git: ref object.GitRepo,- has_git: bool,- old_commit: objid.Id,- commit_tree: objid.Id,- old_parents: list[objid.Id],- new_parents: list[objid.Id],- new_parent_trees: list[objid.Id],- adjacent_merge: bool-) treemerge.Outcome = trust {- val terms: mut list[ref treemerge.TreeTerm] = lists.new[ref treemerge.TreeTerm]()- val maps: mut list[ref rename.RenameMap] = lists.new[ref rename.RenameMap]()- @append(terms, new_term(true, true, commit_tree))- // The commit may have renamed paths relative to its first old parent.- if @len(old_parents) > 0 {- val p0 = @get(old_parents, 0)- if p0 is some oldp {- @append(maps, new_map(handles, git, has_git, oldp, old_commit))- } else {- @append(maps, empty_map())- }- } else {- @append(maps, empty_map())- }- if @len(old_parents) == 0 {- // Root commit onto a new parent: treat the base as absent.- for ntid in new_parent_trees {- @append(terms, new_term(true, !objid.Id.is_none(ntid), ntid))- @append(maps, empty_map())- }- @append(terms, new_term(false, false, objid.id(none)))- @append(maps, empty_map())- } else {- val n: usize = @len(old_parents)- val i: mut usize = 0- for i < n {- val op = @get(old_parents, i)- val np = @get(new_parents, i)- val ot: mut option[objid.Id] = none- if op is some oid {- ot = tree_of(handles, oid)- }- val ntid_o = @get(new_parent_trees, i)- val ntid: mut objid.Id = objid.id(none)- if ntid_o is some tv {- ntid = tv- }- @append(terms, new_term(true, !objid.Id.is_none(ntid), ntid))- @append(terms, new_term(false, has_opt(ot), option_id(ot)))- if op is some ob {- if np is some nb {- @append(maps, new_map(handles, git, has_git, ob, nb))- } else {- @append(maps, empty_map())- }- } else {- @append(maps, empty_map())- }- @append(maps, empty_map())- free_opt(ot)- i++- }- }- val out = treemerge.merge(- repo,- tx,- handles,- git,- has_git,- terms,- maps,- adjacent_merge- )- free_terms(terms)- free_maps(maps)- return out-}--- a/veins/src/merge/filemerge.sx+++ /dev/null@@ -1,686 +0,0 @@-/// Line-based three-way file merge.-///-/// The implementation uses a bounded LCS diff and a diff3-style hunk merge.-/// Binary detection is performed by the caller; this module only deals with-/// text. Line buffers are borrowed from the caller's blob data.--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 blob = use("../object/blob.sx")-val content = use("../object/content.sx")-val store = use("../store/store.sx")-val raw = use("../object/raw.sx")-val txnmod = use("../store/txn.sx")-val object = use("../git/object.sx")--pub val OP_CONTEXT: u8 = 32-pub val OP_ADD: u8 = 43-pub val OP_DEL: u8 = 45--pub type Op = {- tag: mut u8- ai: mut usize- bi: mut usize-}--pub type Hunk = {- start: mut usize- end: mut usize- lines: mut list[bytes.Bytes]-}--pub type Range = {- base_start: mut usize- base_end: mut usize- ours_start: mut usize- ours_end: mut usize- theirs_start: mut usize- theirs_end: mut usize-}--pub type EditResult = {- conflicted: mut bool- data: mut bytes.Bytes- ranges: mut list[ref Range]-}--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()-}--/// Split into lines that retain their trailing newline (except a final line-/// without one). Empty input yields no lines.-pub 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 {- if bytes.Bytes.at(data, i) == 10 {- @append(out, bytes.Bytes.slice(data, start, i + 1))- start = i + 1- }- i++- }- if start < data.len {- @append(out, bytes.Bytes.slice(data, start, data.len))- }- return out-}--pub fn contains_nul(data: bytes.Bytes) bool = trust {- val limit: usize = 8192- val n: usize = data.len- val i: mut usize = 0- for i < n && i < limit {- if bytes.Bytes.at(data, i) == 0 {- return true- }- i++- }- return false-}--fn new_op(tag: u8, ai: usize, bi: usize) ref Op = trust {- val op: mut ref Op = @alloc(@sizeof(Op)) as ref Op- op.tag = tag- op.ai = ai- op.bi = bi- return op-}--fn free_ops(ops: list[ref Op]) void = trust {- for op in ops {- val p: mut ref void = op as ref void- @free(p)- }- @listfree(ops)-}--fn op_at(ops: list[ref Op], i: usize) ref Op = trust {- val o = @get(ops, i)- if o is some op {- return op- }- assert false- return none-}--fn reverse_ops(ops: mut list[ref Op]) void = trust {- val n: usize = @len(ops)- val i: mut usize = 0- for i < n / 2 {- val a: ref Op = op_at(ops, i)- val b: ref Op = op_at(ops, n - 1 - i)- @set(ops, i, b)- @set(ops, n - 1 - i, a)- i++- }-}--fn lcs_get(dp: ref u32, idx: usize) u32 = trust {- val p: ref u32 = @ptradd(dp as ref void, (idx * 4) as i64) as ref u32- return @load32(p) as u32-}--fn lcs_set(dp: ref u32, idx: usize, value: u32) void = trust {- val p: ref u32 = @ptradd(dp as ref void, (idx * 4) as i64) as ref u32- @store32(p, value as i32)-}--/// A bounded LCS diff. If the matrix would exceed the budget, fall back to a-/// common-prefix/suffix replacement, which is conservative but never allocates-/// memory proportional to the product of the file lengths.-fn build_ops(a: list[bytes.Bytes], b: list[bytes.Bytes]) list[ref Op] = trust {- val n: usize = @len(a)- val m: usize = @len(b)- val cells: u64 = ((n as u64) + 1) * ((m as u64) + 1)- if cells > 8000000 {- return fallback_ops(a, b)- }- val cols: usize = m + 1- val dp: ref u32 = @alloc((cells as usize) * 4) as ref u32- @memset(dp as ref void, 0, (cells as usize) * 4)- val i: mut usize = 1- for i <= n {- val j: mut usize = 1- for j <= m {- if bytes.Bytes.eql(line_at(a, i - 1), line_at(b, j - 1)) {- lcs_set(dp, i * cols + j, lcs_get(dp, (i - 1) * cols + (j - 1)) + 1)- } else {- val up: u32 = lcs_get(dp, (i - 1) * cols + j)- val left: u32 = lcs_get(dp, i * cols + (j - 1))- val best: mut u32 = left- if up > best {- best = up- }- lcs_set(dp, i * cols + j, best)- }- j++- }- i++- }- val ops: mut list[ref Op] = lists.new[ref Op]()- val oi: mut usize = n- val oj: mut usize = m- for oi > 0 || oj > 0 {- if oi > 0 && oj > 0 && bytes.Bytes.eql(line_at(a, oi - 1), line_at(b, oj - 1)) {- @append(ops, new_op(OP_CONTEXT, oi - 1, oj - 1))- oi--- oj--- } elif oj > 0- && (oi == 0 || lcs_get(dp, oi * cols + (oj - 1)) >= lcs_get(dp, (oi - 1) * cols + oj)) {- @append(ops, new_op(OP_ADD, 0, oj - 1))- oj--- } else {- @append(ops, new_op(OP_DEL, oi - 1, 0))- oi--- }- }- reverse_ops(ops)- @free(dp as ref void)- return ops-}--fn fallback_ops(a: list[bytes.Bytes], b: list[bytes.Bytes]) list[ref Op] = trust {- val n: usize = @len(a)- val m: usize = @len(b)- val ops: mut list[ref Op] = lists.new[ref Op]()- val prefix: mut usize = 0- for prefix < n && prefix < m {- if !bytes.Bytes.eql(line_at(a, prefix), line_at(b, prefix)) {- break- }- prefix++- }- val suffix: mut usize = 0- for suffix < n - prefix && suffix < m - prefix {- if !bytes.Bytes.eql(- line_at(a, n - 1 - suffix),- line_at(b, m - 1 - suffix)- ) {- break- }- suffix++- }- val i: mut usize = 0- for i < prefix {- @append(ops, new_op(OP_CONTEXT, i, i))- i++- }- val di: mut usize = prefix- for di < n - suffix {- @append(ops, new_op(OP_DEL, di, 0))- di++- }- val ai: mut usize = prefix- for ai < m - suffix {- @append(ops, new_op(OP_ADD, 0, ai))- ai++- }- val s: mut usize = 0- for s < suffix {- @append(ops, new_op(OP_CONTEXT, n - suffix + s, m - suffix + s))- s++- }- return ops-}--fn new_hunk(start: usize, end: usize, lines: list[bytes.Bytes]) ref Hunk = trust {- val h: mut ref Hunk = @alloc(@sizeof(Hunk)) as ref Hunk- h.start = start- h.end = end- h.lines = lines- return h-}--fn free_hunks(hs: list[ref Hunk]) void = trust {- for h in hs {- @listfree(h.lines)- val p: mut ref void = h as ref void- @free(p)- }- @listfree(hs)-}--fn hunk_at(hs: list[ref Hunk], i: usize) ref Hunk = trust {- val o = @get(hs, i)- if o is some h {- return h- }- assert false- return none-}--fn hunks_from_ops(side: list[bytes.Bytes], ops: list[ref Op]) list[ref Hunk] = trust {- val out: mut list[ref Hunk] = lists.new[ref Hunk]()- val nops: usize = @len(ops)- val i: mut usize = 0- val base_pos: mut usize = 0- for i < nops {- val op: ref Op = op_at(ops, i)- if op.tag == OP_CONTEXT {- base_pos++- i++- } else {- val start: usize = base_pos- val lines: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()- for i < nops {- val inner: ref Op = op_at(ops, i)- if inner.tag == OP_CONTEXT {- break- }- if inner.tag == OP_DEL {- base_pos++- } else {- @append(lines, line_at(side, inner.bi))- }- i++- }- @append(out, new_hunk(start, base_pos, lines))- }- }- return out-}--fn diff_hunks(base: list[bytes.Bytes], side: list[bytes.Bytes]) list[ref Hunk] = trust {- val ops: list[ref Op] = build_ops(base, side)- val hs: list[ref Hunk] = hunks_from_ops(side, ops)- free_ops(ops)- return hs-}--pub fn free_edit(r: EditResult) void = trust {- if r.data.ptr != none {- val dp: mut ref void = r.data.ptr as ref void- @free(dp)- }- for x in r.ranges {- val xp: mut ref void = x as ref void- @free(xp)- }- @listfree(r.ranges)-}--fn append_range(- out: mut buf.Buf,- lines: list[bytes.Bytes],- start: usize,- end: usize-) void = trust {- val i: mut usize = start- for i < end && i < @len(lines) {- buf.Buf.put_bytes(out, line_at(lines, i))- i++- }-}--fn apply_hunks(- out: mut buf.Buf,- base: list[bytes.Bytes],- from: usize,- to: usize,- hs: list[ref Hunk],- first: usize,- last: usize-) void = trust {- val pos: mut usize = from- val k: mut usize = first- for k < last {- val h: ref Hunk = hunk_at(hs, k)- if h.start > pos && h.start <= to {- append_range(out, base, pos, h.start)- }- for l in h.lines {- buf.Buf.put_bytes(out, l)- }- if h.end > pos {- pos = h.end- }- k++- }- if pos < to {- append_range(out, base, pos, to)- }-}--fn map_pos(hs: list[ref Hunk], pos: usize) usize = trust {- val out: mut usize = pos- for h in hs {- if h.end <= pos {- val old: usize = h.end - h.start- val new: usize = @len(h.lines)- if new >= old {- out = out + (new - old)- } else {- out = out - (old - new)- }- } elif h.start < pos {- val old: usize = pos - h.start- val new: usize = @len(h.lines)- if new >= old {- out = out + (new - old)- } else {- out = out - (old - new)- }- break- } else {- break- }- }- return out-}--fn same_hunks(- ours: list[ref Hunk],- of: usize,- ol: usize,- theirs: list[ref Hunk],- tf: usize,- tl: usize-) bool = trust {- val a_buf: mut buf.Buf = buf.new(64)- val b_buf: mut buf.Buf = buf.new(64)- val k: mut usize = of- for k < ol {- val h = hunk_at(ours, k)- for l in h.lines {- buf.Buf.put_bytes(a_buf, l)- }- k++- }- val j: mut usize = tf- for j < tl {- val h2 = hunk_at(theirs, j)- for l2 in h2.lines {- buf.Buf.put_bytes(b_buf, l2)- }- j++- }- val same: bool = bytes.Bytes.eql(buf.Buf.view(a_buf), buf.Buf.view(b_buf))- buf.Buf.free(a_buf)- buf.Buf.free(b_buf)- return same-}--/// Merge three line lists. The returned data is owned by the caller.-pub fn merge_lines(- base: list[bytes.Bytes],- ours: list[bytes.Bytes],- theirs: list[bytes.Bytes],- adjacent_merge: bool-) EditResult = trust {- val ours_h: list[ref Hunk] = diff_hunks(base, ours)- val theirs_h: list[ref Hunk] = diff_hunks(base, theirs)- val out: mut buf.Buf = buf.new(4096)- val ranges: mut list[ref Range] = lists.new[ref Range]()- val conflicted: mut bool = false-- val oi: mut usize = 0- val ti: mut usize = 0- val pos: mut usize = 0- for oi < @len(ours_h) || ti < @len(theirs_h) {- val o_start: mut usize = 0- val t_start: mut usize = 0- val have_o: mut bool = false- val have_t: mut bool = false- if oi < @len(ours_h) {- o_start = hunk_at(ours_h, oi).start- have_o = true- }- if ti < @len(theirs_h) {- t_start = hunk_at(theirs_h, ti).start- have_t = true- }- val take_ours_cluster: mut bool = false- if have_o && (!have_t || o_start <= t_start) {- take_ours_cluster = true- }- val cluster_start: mut usize = t_start- if take_ours_cluster {- cluster_start = o_start- }- val of: usize = oi- val tf: usize = ti- val mut_o_last: mut usize = of- val mut_t_last: mut usize = tf- val mut_end: mut usize = cluster_start- val mut_seen_o: mut bool = false- val mut_seen_t: mut bool = false- for {- val mut_progress: mut bool = false- if mut_o_last < @len(ours_h) {- val h: ref Hunk = hunk_at(ours_h, mut_o_last)- val include: mut bool = h.start <= mut_end- if mut_o_last == of {- include = h.start <= mut_end- } elif adjacent_merge {- include = h.start < mut_end- } else {- include = h.start <= mut_end- }- if include {- mut_seen_o = true- mut_o_last++- if h.end > mut_end {- mut_end = h.end- }- mut_progress = true- }- }- if mut_t_last < @len(theirs_h) {- val h2: ref Hunk = hunk_at(theirs_h, mut_t_last)- val include2: mut bool = h2.start <= mut_end- if mut_t_last == tf {- include2 = h2.start <= mut_end- } elif adjacent_merge {- include2 = h2.start < mut_end- } else {- include2 = h2.start <= mut_end- }- if include2 {- mut_seen_t = true- mut_t_last++- if h2.end > mut_end {- mut_end = h2.end- }- mut_progress = true- }- }- if !mut_progress {- break- }- }- if mut_end < cluster_start {- mut_end = cluster_start- }- if mut_seen_o && !mut_seen_t {- apply_hunks(out, base, pos, mut_end, ours_h, of, mut_o_last)- pos = mut_end- oi = mut_o_last- ti = mut_t_last- } elif mut_seen_t && !mut_seen_o {- apply_hunks(out, base, pos, mut_end, theirs_h, tf, mut_t_last)- pos = mut_end- oi = mut_o_last- ti = mut_t_last- } else {- if same_hunks(ours_h, of, mut_o_last, theirs_h, tf, mut_t_last) {- apply_hunks(out, base, pos, mut_end, ours_h, of, mut_o_last)- pos = mut_end- } else {- conflicted = true- apply_hunks(out, base, pos, mut_end, ours_h, of, mut_o_last)- val r: mut ref Range = @alloc(@sizeof(Range)) as ref Range- r.base_start = cluster_start- r.base_end = mut_end- r.ours_start = map_pos(ours_h, cluster_start)- r.ours_end = map_pos(ours_h, mut_end)- r.theirs_start = map_pos(theirs_h, cluster_start)- r.theirs_end = map_pos(theirs_h, mut_end)- @append(ranges, r)- pos = mut_end- }- oi = mut_o_last- ti = mut_t_last- }- }- if pos < @len(base) {- append_range(out, base, pos, @len(base))- }- val data: bytes.Bytes = bytes.Bytes.dup(buf.Buf.view(out))- buf.Buf.free(out)- free_hunks(ours_h)- free_hunks(theirs_h)- return EditResult{conflicted: conflicted, data: data, ranges: ranges}-}--/// Merge three blob contents. Returns the merged text (owned) and ranges.-fn merge_blobs_inner(- handles: list[ref store.Handle],- git: ref object.GitRepo,- has_git: bool,- base_id: objid.Id,- ours_id: objid.Id,- theirs_id: objid.Id,- adjacent_merge: bool,- use_cache: bool,- tx: ref txnmod.Txn-) option[EditResult] = trust {- val b_opt: mut option[bytes.Bytes] = none- val o_opt: mut option[bytes.Bytes] = none- val t_opt: mut option[bytes.Bytes] = none- if use_cache {- b_opt = content.read_blob_tx(handles, base_id, git, has_git, tx)- o_opt = content.read_blob_tx(handles, ours_id, git, has_git, tx)- t_opt = content.read_blob_tx(handles, theirs_id, git, has_git, tx)- } else {- b_opt = content.read_blob(handles, base_id, git, has_git)- o_opt = content.read_blob(handles, ours_id, git, has_git)- t_opt = content.read_blob(handles, theirs_id, git, has_git)- }- if !has_read(b_opt) || !has_read(o_opt) || !has_read(t_opt) {- free_read(b_opt)- free_read(o_opt)- free_read(t_opt)- return none- }- val b = lines_of(b_opt)- val o = lines_of(o_opt)- val t = lines_of(t_opt)- val result: EditResult = merge_lines(b, o, t, adjacent_merge)- @listfree(b)- @listfree(o)- @listfree(t)- free_read(b_opt)- free_read(o_opt)- free_read(t_opt)- return some result-}--pub fn merge_blobs(- handles: list[ref store.Handle],- git: ref object.GitRepo,- has_git: bool,- base_id: objid.Id,- ours_id: objid.Id,- theirs_id: objid.Id,- adjacent_merge: bool-) option[EditResult] = trust {- return merge_blobs_inner(- handles,- git,- has_git,- base_id,- ours_id,- theirs_id,- adjacent_merge,- false,- none- )-}--pub fn merge_blobs_tx(- handles: list[ref store.Handle],- git: ref object.GitRepo,- has_git: bool,- base_id: objid.Id,- ours_id: objid.Id,- theirs_id: objid.Id,- adjacent_merge: bool,- tx: ref txnmod.Txn-) option[EditResult] = trust {- return merge_blobs_inner(- handles,- git,- has_git,- base_id,- ours_id,- theirs_id,- adjacent_merge,- true,- tx- )-}--fn lines_of(d: option[bytes.Bytes]) list[bytes.Bytes] = trust {- if d is some data {- return split_lines(data)- }- return lists.new[bytes.Bytes]()-}--fn has_read(d: option[bytes.Bytes]) bool = trust {- if d is some _ {- return true- }- return false-}--fn free_read(d: option[bytes.Bytes]) void = trust {- if d is some data {- @free(data.ptr as ref void)- }-}--/// Build a blob object for `lines` and add it to the transaction.-pub fn add_blob(- tx: mut ref txnmod.Txn,- lines: list[bytes.Bytes]-) objid.Id = trust {- val b: mut buf.Buf = buf.new(4096)- for l in lines {- buf.Buf.put_bytes(b, l)- }- val built: ref blob.BlobBuild = blob.build(b.ptr, b.len)- val id: objid.Id = copy_root(built)- val i: mut usize = 0- for i < @len(built.objects) {- val ro = @get(built.objects, i)- if ro is some obj {- val orf: mut ref raw.RawObject = obj- val oid: objid.Id = objid.id(orf.id)- val _ = txnmod.add_known(tx, orf.type_byte, oid, orf.body)- orf.body = bytes.empty()- }- i++- }- blob.free_build(built)- buf.Buf.free(b)- return id-}--fn copy_root(built: ref blob.BlobBuild) objid.Id = trust {- val id: objid.Id = blob.root_id(built)- val out: ref u8 = @alloc(32) as ref u8- @memcpy(out as ref void, id.ptr as ref void, 32)- return objid.id(out)-}--- a/veins/src/merge/rename.sx+++ /dev/null@@ -1,743 +0,0 @@-/// Rename detection and rename maps used by the merge engine.-///-/// Recorded renames (`renames_state = 1`) are authoritative. Imported commits-/// use heuristics: exact content matches first, then a similarity score based-/// on chunk IDs for large blobs and lines for small ones.--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 blob = use("../object/blob.sx")-val content = use("../object/content.sx")-val graph = use("../object/graph.sx")-val store = use("../store/store.sx")-val state = use("../store/state.sx")-val object = use("../git/object.sx")-val files = use("../io/files.sx")-val txnmod = use("../store/txn.sx")--pub type Entry = {- from: mut bytes.Bytes- to: mut bytes.Bytes-}--pub type RenameMap = {- entries: mut list[ref Entry]-}--pub fn empty() RenameMap = {- return RenameMap{entries: lists.new[ref Entry]()}-}--fn new_entry(from: bytes.Bytes, to: bytes.Bytes) ref Entry = {- val e: mut ref Entry = @alloc(@sizeof(Entry)) as ref Entry- e.from = bytes.Bytes.dup(from)- e.to = bytes.Bytes.dup(to)- return e-}--pub fn free_map(m: RenameMap) void = trust {- for e in m.entries {- if e.from.ptr != none {- val fp: mut ref void = e.from.ptr as ref void- @free(fp)- }- if e.to.ptr != none {- val tp: mut ref void = e.to.ptr as ref void- @free(tp)- }- val ep: mut ref void = e as ref void- @free(ep)- }- @listfree(m.entries)-}--/// Look up the destination of a base path. The result is borrowed.-pub fn lookup(m: RenameMap, path: bytes.Bytes) option[bytes.Bytes] = trust {- for e in m.entries {- if bytes.Bytes.eql(e.from, path) {- return some e.to- }- }- return none-}--fn apply(m: mut RenameMap, from: bytes.Bytes, to: bytes.Bytes) void = trust {- // Compose a -> b followed by b -> c into a -> c.- val composed: mut bool = false- for e in m.entries {- val em: mut ref Entry = e- if bytes.Bytes.eql(em.to, from) {- if em.to.ptr != none {- val tp: mut ref void = em.to.ptr as ref void- @free(tp)- }- em.to = bytes.Bytes.dup(to)- composed = true- }- }- if composed {- return- }- for e in m.entries {- val em: mut ref Entry = e- if bytes.Bytes.eql(em.from, from) {- if em.to.ptr != none {- val tp: mut ref void = em.to.ptr as ref void- @free(tp)- }- em.to = bytes.Bytes.dup(to)- return- }- }- @append(m.entries, new_entry(from, to))-}--fn first_parent(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 {- out = some graph.copy_id(pid)- }- }- graph.free_loaded(lc)- }- return out-}--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 hash_line(line: bytes.Bytes) u64 = {- val h: mut u64 = 1469598103934665603- val i: mut usize = 0- for i < line.len {- h = (h ^ (bytes.Bytes.at(line, i) as u64)) * 1099511628211- i++- }- return h-}--fn sort_u64(xs: mut list[u64]) void = trust {- val n: usize = @len(xs)- val i: mut usize = 1- for i < n {- val cur = @get(xs, i)- val c: mut u64 = 0- if cur is some v {- c = v- }- val j: mut usize = i- for j > 0 {- val prev_o = @get(xs, j - 1)- val prev: mut u64 = 0- if prev_o is some vv {- prev = vv- }- if prev <= c {- break- }- @set(xs, j, prev)- j--- }- @set(xs, j, c)- i++- }-}--fn line_similarity(a: bytes.Bytes, b: bytes.Bytes) i32 = trust {- val la: mut list[u64] = lists.new[u64]()- val lb: mut list[u64] = lists.new[u64]()- val start_a: mut usize = 0- val i: mut usize = 0- for i <= a.len {- if i == a.len || bytes.Bytes.at(a, i) == 10 {- @append(la, hash_line(bytes.Bytes.slice(a, start_a, i)))- start_a = i + 1- }- i++- }- val start_b: mut usize = 0- val j: mut usize = 0- for j <= b.len {- if j == b.len || bytes.Bytes.at(b, j) == 10 {- @append(lb, hash_line(bytes.Bytes.slice(b, start_b, j)))- start_b = j + 1- }- j++- }- sort_u64(la)- sort_u64(lb)- val ia: mut usize = 0- val ib: mut usize = 0- val inter: mut usize = 0- for ia < @len(la) && ib < @len(lb) {- val va = @get(la, ia)- val vb = @get(lb, ib)- val a_val: mut u64 = 0- val b_val: mut u64 = 0- if va is some x {- a_val = x- }- if vb is some y {- b_val = y- }- if a_val == b_val {- inter++- ia++- ib++- } elif a_val < b_val {- ia++- } else {- ib++- }- }- val total_union: usize = @len(la) + @len(lb) - inter- @listfree(la)- @listfree(lb)- if total_union == 0 {- return 100- }- return ((inter * 100) / total_union) as i32-}--fn read_body_any(- handles: list[ref store.Handle],- id: objid.Id,- expected: u8,- use_cache: bool,- tx: ref txnmod.Txn-) option[bytes.Bytes] = trust {- if use_cache {- val cached = txnmod.find_cached(tx, expected, id)- if cached is some b {- return some bytes.Bytes.dup(b)- }- }- return state.read_body(handles, id, expected)-}--fn chunk_ids(- handles: list[ref store.Handle],- id: objid.Id,- out: mut list[objid.Id],- depth: usize,- use_cache: bool,- tx: ref txnmod.Txn-) bool = trust {- if depth > 64 {- return false- }- val body_opt = read_body_any(handles, id, types.BLOB, use_cache, tx)- 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_LEAF {- for e in b.entries {- val cp: ref u8 = @alloc(32) as ref u8- @memcpy(cp as ref void, e.id.ptr as ref void, 32)- @append(out, objid.id(cp))- }- } elif b.form == blob.FORM_INTERIOR {- for e in b.entries {- if !chunk_ids(handles, e.id, out, depth + 1, use_cache, tx) {- good = false- break- }- }- }- blob.free_blob(b)- files.free_buffer(body)- return good-}--fn chunk_similarity(- handles: list[ref store.Handle],- a: objid.Id,- b: objid.Id,- use_cache: bool,- tx: ref txnmod.Txn-) i32 = trust {- val ca: mut list[objid.Id] = lists.new[objid.Id]()- val cb: mut list[objid.Id] = lists.new[objid.Id]()- val oka: bool = chunk_ids(handles, a, ca, 0, use_cache, tx)- val okb: bool = chunk_ids(handles, b, cb, 0, use_cache, tx)- val result: mut i32 = 0- if oka && okb {- val inter: mut usize = 0- for x in ca {- for y in cb {- if objid.Id.eql(x, y) {- inter++- break- }- }- }- val total_union: usize = @len(ca) + @len(cb) - inter- if total_union > 0 {- result = ((inter * 100) / total_union) as i32- }- }- graph.free_ids(ca)- graph.free_ids(cb)- return result-}--/// Similarity in percent. Uses chunk IDs for large blobs and line overlap for-/// small ones. Returns 0 when either blob cannot be read.-pub fn similarity(- handles: list[ref store.Handle],- git: ref object.GitRepo,- has_git: bool,- a: objid.Id,- b: objid.Id,- use_cache: bool,- tx: ref txnmod.Txn-) i32 = trust {- if objid.Id.eql(a, b) {- return 100- }- val ca = content.read_blob_tx(handles, a, git, has_git, tx)- val cb = content.read_blob_tx(handles, b, git, has_git, tx)- if ca is some da {- if cb is some db {- val res: mut i32 = 0- if da.len >= 131072 && db.len >= 131072 {- res = chunk_similarity(handles, a, b, use_cache, tx)- }- if res == 0 {- res = line_similarity(da, db)- }- files.free_buffer(da)- files.free_buffer(db)- return res- }- files.free_buffer(da)- return 0- }- if cb is some db2 {- files.free_buffer(db2)- }- return 0-}--type Pair = {- old_path: mut bytes.Bytes- new_path: mut bytes.Bytes- old_id: mut objid.Id- new_id: mut objid.Id- score: mut i32- old_used: mut bool- new_used: mut bool-}--fn new_pair(- old_path: bytes.Bytes,- new_path: bytes.Bytes,- old_id: objid.Id,- new_id: objid.Id,- score: i32-) ref Pair = trust {- val p: mut ref Pair = @alloc(@sizeof(Pair)) as ref Pair- p.old_path = old_path- p.new_path = new_path- p.old_id = graph.copy_id(old_id)- p.new_id = graph.copy_id(new_id)- p.score = score- p.old_used = false- p.new_used = false- return p-}--fn free_pairs(ps: list[ref Pair]) void = trust {- for p in ps {- val op: mut ref void = p.old_id.ptr as ref void- @free(op)- val np: mut ref void = p.new_id.ptr as ref void- @free(np)- val pp: mut ref void = p as ref void- @free(pp)- }- @listfree(ps)-}--pub fn sort_renames(rs: mut list[ref commit.Rename]) void = trust {- val i: mut usize = 1- for i < @len(rs) {- val cur = @get(rs, i)- val c: mut ref commit.Rename = 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 commit.Rename = none- if prev_o is some vv {- prev = vv- }- val cmp: mut i64 = bytes.Bytes.cmp(prev.to_path, c.to_path)- if prev.parent_index < c.parent_index {- cmp = -1- } elif prev.parent_index > c.parent_index {- cmp = 1- }- if cmp <= 0 {- break- }- @set(rs, j, prev)- j--- }- @set(rs, j, c)- i++- }-}--/// Detect renames between two trees. `similar_pct` is 0 to disable similarity-/// matching. Returned renames are sorted by `(parent_index, to_path)`.-fn detect_inner(- handles: list[ref store.Handle],- git: ref object.GitRepo,- has_git: bool,- old_tree: option[objid.Id],- new_tree: option[objid.Id],- similar_pct: i32,- parent_index: u64,- use_cache: bool,- tx: ref txnmod.Txn-) list[ref commit.Rename] = trust {- val old: mut list[ref treewalk.FlatEntry] = lists.new[ref treewalk.FlatEntry]()- val new: mut list[ref treewalk.FlatEntry] = lists.new[ref treewalk.FlatEntry]()- if use_cache {- old = treewalk.flatten_or_empty_tx(handles, old_tree, tx)- new = treewalk.flatten_or_empty_tx(handles, new_tree, tx)- } else {- old = treewalk.flatten_or_empty(handles, old_tree)- new = treewalk.flatten_or_empty(handles, new_tree)- }- val out: mut list[ref commit.Rename] = lists.new[ref commit.Rename]()- val deleted: mut list[ref treewalk.FlatEntry] = lists.new[ref treewalk.FlatEntry]()- val added: mut list[ref treewalk.FlatEntry] = lists.new[ref treewalk.FlatEntry]()- for e in old {- if treewalk.lookup(new, e.path) is none {- @append(deleted, e)- }- }- for n in new {- if treewalk.lookup(old, n.path) is none {- @append(added, n)- }- }- val used_old: ref u8 = @alloc(@len(deleted) + 1) as ref u8- @memset(used_old as ref void, 0, @len(deleted) + 1)- val used_new: ref u8 = @alloc(@len(added) + 1) as ref u8- @memset(used_new as ref void, 0, @len(added) + 1)-- // Exact content matches first.- val di: mut usize = 0- for di < @len(deleted) {- val d = @get(deleted, di)- if d is some de {- if @load8(@ptradd(used_old, di as i64)) == 0 {- val ai: mut usize = 0- for ai < @len(added) {- val a = @get(added, ai)- if a is some ae {- if @load8(@ptradd(used_new, ai as i64)) == 0- && objid.Id.eql(de.target, ae.target) {- @append(- out,- commit.new_rename(- parent_index,- 0,- bytes.Bytes.dup(de.path),- bytes.Bytes.dup(ae.path)- )- )- @store8(@ptradd(used_old, di as i64), 1)- @store8(@ptradd(used_new, ai as i64), 1)- break- }- }- ai++- }- }- }- di++- }-- if similar_pct > 0 {- val pairs: mut list[ref Pair] = lists.new[ref Pair]()- val candidate_limit: usize = 5000- val di2: mut usize = 0- for di2 < @len(deleted) {- val d = @get(deleted, di2)- if d is some de {- if @load8(@ptradd(used_old, di2 as i64)) == 0- && (de.kind == tree.KIND_FILE || de.kind == tree.KIND_EXECUTABLE) {- val ai2: mut usize = 0- for ai2 < @len(added) && @len(pairs) < candidate_limit {- val a = @get(added, ai2)- if a is some ae {- if @load8(@ptradd(used_new, ai2 as i64)) == 0- && (ae.kind == tree.KIND_FILE || ae.kind == tree.KIND_EXECUTABLE) {- @append(- pairs,- new_pair(- de.path,- ae.path,- de.target,- ae.target,- similarity(- handles,- git,- has_git,- de.target,- ae.target,- use_cache,- tx- )- )- )- }- }- ai2++- }- }- }- di2++- }- // Greedy best-score assignment.- for {- val best: mut i32 = -1- val best_i: mut i32 = -1- val pi: mut usize = 0- for pi < @len(pairs) {- val p = @get(pairs, pi)- if p is some pp {- if !pp.old_used && !pp.new_used && pp.score > best {- best = pp.score- best_i = pi as i32- }- }- pi++- }- if best_i < 0 || best < similar_pct {- break- }- val chosen = @get(pairs, best_i as usize)- if chosen is some cp {- cp.old_used = true- cp.new_used = true- @append(- out,- commit.new_rename(- parent_index,- 0,- bytes.Bytes.dup(cp.old_path),- bytes.Bytes.dup(cp.new_path)- )- )- }- }- free_pairs(pairs)- }-- @free(used_old as ref void)- @free(used_new as ref void)- // `deleted` and `added` hold borrowed pointers into `old` and `new`.- @listfree(deleted)- @listfree(added)- treewalk.free_flat(old)- treewalk.free_flat(new)- sort_renames(out)- return out-}--pub fn detect(- handles: list[ref store.Handle],- git: ref object.GitRepo,- has_git: bool,- old_tree: option[objid.Id],- new_tree: option[objid.Id],- similar_pct: i32,- parent_index: u64-) list[ref commit.Rename] = trust {- return detect_inner(- handles,- git,- has_git,- old_tree,- new_tree,- similar_pct,- parent_index,- false,- none- )-}--pub fn detect_tx(- handles: list[ref store.Handle],- git: ref object.GitRepo,- has_git: bool,- old_tree: option[objid.Id],- new_tree: option[objid.Id],- similar_pct: i32,- parent_index: u64,- tx: ref txnmod.Txn-) list[ref commit.Rename] = trust {- return detect_inner(- handles,- git,- has_git,- old_tree,- new_tree,- similar_pct,- parent_index,- true,- tx- )-}--fn apply_commit(- handles: list[ref store.Handle],- git: ref object.GitRepo,- has_git: bool,- cid: objid.Id,- m: mut RenameMap-) void = trust {- val lc_opt = graph.load_commit(handles, cid)- val lc: mut ref graph.LoadedCommit = none- match lc_opt {- some lc0 => {- lc = lc0- }- none => {- return- }- }- if lc.c.renames_state == commit.RENAMES_RECORDED {- for r in lc.c.renames {- if r.parent_index == 0 {- apply(m, r.from_path, r.to_path)- }- }- } else {- val parent_opt = first_parent(handles, cid)- if parent_opt is some pid {- val pt = tree_of(handles, pid)- val ct = tree_of(handles, cid)- val rs = detect(handles, git, has_git, pt, ct, 50, 0)- for r in rs {- apply(m, r.from_path, r.to_path)- 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)- free_tree_opt(pt)- free_tree_opt(ct)- }- }- graph.free_loaded(lc)-}--fn free_tree_opt(t: option[objid.Id]) void = trust {- if t is some id {- val p: mut ref void = id.ptr as ref void- @free(p)- }-}--/// Compute the rename map from `base` to `side`.-pub fn map_from(- handles: list[ref store.Handle],- git: ref object.GitRepo,- has_git: bool,- base: objid.Id,- side: objid.Id-) RenameMap = trust {- val m: mut RenameMap = empty()- if objid.Id.eql(base, side) {- return m- }- // Follow the first-parent chain from the side back to the base.- val chain: mut list[objid.Id] = lists.new[objid.Id]()- val cur: mut objid.Id = graph.copy_id(side)- val reached: mut bool = false- val depth: mut usize = 0- for depth < 100000 {- if objid.Id.eql(cur, base) {- reached = true- @free(cur.ptr as ref void)- cur = objid.Id{ptr: none}- break- }- @append(chain, cur)- val p = first_parent(handles, cur)- if p is some pid {- cur = pid- } else {- cur = objid.Id{ptr: none}- break- }- depth++- }- if cur.ptr != none {- @free(cur.ptr as ref void)- }- if !reached {- graph.free_ids(chain)- return m- }- // chain is side .. child-of-base; apply in reverse.- val i: mut usize = @len(chain)- for i > 0 {- i--- val o = @get(chain, i)- if o is some cid {- apply_commit(handles, git, has_git, cid, m)- }- }- graph.free_ids(chain)- return m-}--- a/veins/src/merge/resolutions.sx+++ /dev/null@@ -1,72 +0,0 @@-/// Resolution memory (`.veins/resolutions/`).-///-/// The key is BLAKE3 of the simplified conflict object body. The value is the-/// resolved blob ID, stored as hex text. Only exact conflict matches are reused.--val str = use("std/string")-val bytes = use("../core/bytes.sx")-val objid = use("../object/id.sx")-val b3 = use("../crypto/blake3.sx")-val layout = use("../store/layout.sx")-val files = use("../io/files.sx")--fn key_hex(body: bytes.Bytes) ref u8 = trust {- val digest: ref u8 = @alloc(32) as ref u8- b3.hash(body.ptr, body.len, digest)- val out: ref u8 = @alloc(65) as ref u8- objid.hex_encode(digest, 32, out)- @store8(@ptradd(out, 64), 0)- @free(digest as ref void)- return out-}--fn key_path(repo: layout.Repo, key: ref u8) str.StringView = trust {- val dir: str.StringView = layout.resolutions_dir(repo)- val path: str.StringView = files.join(dir, str.from_cstr(key))- files.free_path(dir)- return path-}--/// Look up the recorded resolution for a conflict body.-pub fn lookup(repo: layout.Repo, body: bytes.Bytes) option[objid.Id] = trust {- val key: ref u8 = key_hex(body)- val path: str.StringView = key_path(repo, key)- val data_opt = files.read_all(path)- files.free_path(path)- @free(key as ref void)- val data: mut bytes.Bytes = bytes.empty()- match data_opt {- some d => {- data = d- }- none => {- return none- }- }- val result: mut option[objid.Id] = none- if data.len >= 64 {- val raw: ref u8 = @alloc(32) as ref u8- if objid.hex_decode(data.ptr, 32, raw) {- result = some objid.id(raw)- } else {- @free(raw as ref void)- }- }- files.free_buffer(data)- return result-}--/// Record that the conflict with `body` resolves to `blob`.-pub fn record(repo: layout.Repo, body: bytes.Bytes, blob: objid.Id) bool = trust {- if blob.ptr == none {- return false- }- val key: ref u8 = key_hex(body)- val path: str.StringView = key_path(repo, key)- val hex: ref u8 = objid.Id.hex(blob)- val wrote: bool = files.write_all(path, bytes.bytes(hex, 64))- @free(hex as ref void)- files.free_path(path)- @free(key as ref void)- return wrote-}--- a/veins/src/merge/treemerge.sx+++ /dev/null@@ -1,842 +0,0 @@-/// Tree-level merge: flatten signed tree terms, apply renames, merge each path,-/// and rebuild a canonical tree.--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 treewalk = use("../object/treewalk.sx")-val conflict = use("../object/conflict.sx")-val store = use("../store/store.sx")-val txnmod = use("../store/txn.sx")-val layout = use("../store/layout.sx")-val object = use("../git/object.sx")-val algebra = use("algebra.sx")-val filemerge = use("filemerge.sx")-val rename = use("rename.sx")-val resolutions = use("resolutions.sx")-val attributes = use("attributes.sx")--pub type TreeTerm = {- positive: mut bool- present: mut bool- id: mut objid.Id-}--pub type EntryTerm = {- positive: mut bool- present: mut bool- kind: mut u8- target: mut objid.Id-}--pub type Outcome = {- tree: mut objid.Id- rerere: mut usize-}--type OrigEntry = {- term: mut usize- path: mut bytes.Bytes- kind: mut u8- target: mut objid.Id-}--type OutEntry = {- path: mut bytes.Bytes- kind: mut u8- target: 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 free_id(id: objid.Id) void = trust {- if id.ptr != none {- val p: mut ref void = id.ptr as ref void- @free(p)- }-}--fn new_orig(term: usize, path: bytes.Bytes, kind: u8, target: objid.Id) ref OrigEntry = trust {- val e: mut ref OrigEntry = @alloc(@sizeof(OrigEntry)) as ref OrigEntry- e.term = term- e.path = bytes.Bytes.dup(path)- e.kind = kind- e.target = copy_id(target)- return e-}--fn free_orig(es: list[ref OrigEntry]) void = trust {- for e in es {- if e.path.ptr != none {- val pp: mut ref void = e.path.ptr as ref void- @free(pp)- }- free_id(e.target)- val ep: mut ref void = e as ref void- @free(ep)- }- @listfree(es)-}--fn new_out(path: bytes.Bytes, kind: u8, target: objid.Id) ref OutEntry = trust {- val e: mut ref OutEntry = @alloc(@sizeof(OutEntry)) as ref OutEntry- e.path = bytes.Bytes.dup(path)- e.kind = kind- e.target = copy_id(target)- return e-}--fn free_out(es: list[ref OutEntry]) void = trust {- for e in es {- if e.path.ptr != none {- val pp: mut ref void = e.path.ptr as ref void- @free(pp)- }- free_id(e.target)- val ep: mut ref void = e as ref void- @free(ep)- }- @listfree(es)-}--fn find_orig(- es: list[ref OrigEntry],- term: usize,- path: bytes.Bytes-) option[ref OrigEntry] = trust {- for e in es {- if e.term == term && bytes.Bytes.eql(e.path, path) {- return some e- }- }- return none-}--fn has_prefix(path: bytes.Bytes, prefix: bytes.Bytes) bool = trust {- if path.len <= prefix.len {- return false- }- if !bytes.Bytes.starts_with(path, prefix) {- return false- }- return bytes.Bytes.at(path, prefix.len) == 47-}--fn list_has_path(xs: list[bytes.Bytes], path: bytes.Bytes) bool = trust {- for x in xs {- if bytes.Bytes.eql(x, path) {- return true- }- }- return false-}--fn sort_out(xs: mut list[ref OutEntry]) void = trust {- val i: mut usize = 1- for i < @len(xs) {- val cur = @get(xs, i)- val c: mut ref OutEntry = none- if cur is some v {- c = v- }- val j: mut usize = i- for j > 0 {- val prev_o = @get(xs, j - 1)- val prev: mut ref OutEntry = none- if prev_o is some vv {- prev = vv- }- if bytes.Bytes.cmp(prev.path, c.path) <= 0 {- break- }- @set(xs, j, prev)- j--- }- @set(xs, j, c)- i++- }-}--fn sort_paths(xs: mut list[bytes.Bytes]) void = trust {- val i: mut usize = 1- for i < @len(xs) {- val cur = @get(xs, i)- val c: mut bytes.Bytes = bytes.empty()- if cur is some v {- c = v- }- val j: mut usize = i- for j > 0 {- val prev_o = @get(xs, j - 1)- val prev: mut bytes.Bytes = bytes.empty()- if prev_o is some vv {- prev = vv- }- if bytes.Bytes.cmp(prev, c) <= 0 {- break- }- @set(xs, j, prev)- j--- }- @set(xs, j, c)- i++- }-}--fn empty_tree(tx: mut ref txnmod.Txn) objid.Id = trust {- val entries: list[ref tree.TreeEntry] = lists.new[ref tree.TreeEntry]()- val encoded = tree.encode(entries)- val body: mut bytes.Bytes = bytes.empty()- match encoded {- ok b => {- body = b- }- err _ => {- return objid.id(none)- }- }- val id: objid.Id = txnmod.add_object(tx, types.TREE, body)- @listfree(entries)- return id-}--fn component_end(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 build_level(- tx: mut ref txnmod.Txn,- entries: list[ref OutEntry],- start: usize,- end: usize,- prefix_len: usize-) objid.Id = trust {- val out: mut list[ref tree.TreeEntry] = lists.new[ref tree.TreeEntry]()- val i: mut usize = start- for i < end {- val e_o = @get(entries, i)- if e_o is some e {- val name_end: usize = component_end(e.path, prefix_len)- val name: bytes.Bytes = bytes.Bytes.slice(e.path, prefix_len, name_end)- if name_end == e.path.len {- @append(out, tree.entry(bytes.Bytes.dup(name), e.kind, e.target))- i++- } else {- val j: mut usize = i + 1- for j < end {- val f_o = @get(entries, j)- if f_o is some f {- val f_end: usize = component_end(f.path, prefix_len)- if f_end != name_end {- break- }- val f_name: bytes.Bytes = bytes.Bytes.slice(f.path, prefix_len, f_end)- if !bytes.Bytes.eql(f_name, name) {- break- }- }- j++- }- val child: objid.Id = build_level(tx, entries, i, j, name_end + 1)- @append(out, tree.entry(bytes.Bytes.dup(name), tree.KIND_SUBTREE, child))- i = j- }- } else {- i++- }- }- val encoded = tree.encode(out)- val body: mut bytes.Bytes = bytes.empty()- match encoded {- ok b => {- body = b- }- err _ => {- for e in out {- if e.name.ptr != none {- val np: mut ref void = e.name.ptr as ref void- @free(np)- }- val ep: mut ref void = e as ref void- @free(ep)- }- @listfree(out)- return objid.id(none)- }- }- val id: objid.Id = txnmod.add_object(tx, types.TREE, body)- for e in out {- if e.name.ptr != none {- val np: mut ref void = e.name.ptr as ref void- @free(np)- }- val ep: mut ref void = e as ref void- @free(ep)- }- @listfree(out)- return id-}--fn build_from_entries(tx: mut ref txnmod.Txn, entries: mut list[ref OutEntry]) objid.Id = trust {- if @len(entries) == 0 {- return empty_tree(tx)- }- sort_out(entries)- return build_level(tx, entries, 0, @len(entries), 0)-}--fn build_subtree(- tx: mut ref txnmod.Txn,- canon: list[ref OrigEntry],- term: usize,- prefix: bytes.Bytes-) objid.Id = trust {- val rels: mut list[ref OutEntry] = lists.new[ref OutEntry]()- for e in canon {- if e.term == term && has_prefix(e.path, prefix) {- val rel: bytes.Bytes = bytes.Bytes.slice(e.path, prefix.len + 1, e.path.len)- @append(rels, new_out(rel, e.kind, e.target))- }- }- val id: objid.Id = build_from_entries(tx, rels)- free_out(rels)- return id-}--fn make_terms(- handles: list[ref store.Handle],- terms: list[ref TreeTerm],- tx: ref txnmod.Txn-) list[ref OrigEntry] = trust {- val out: mut list[ref OrigEntry] = lists.new[ref OrigEntry]()- val i: mut usize = 0- for i < @len(terms) {- val o = @get(terms, i)- if o is some t {- if t.present {- val flat: list[ref treewalk.FlatEntry] = treewalk.flatten_tx(handles, t.id, tx)- for e in flat {- @append(out, new_orig(i, e.path, e.kind, e.target))- }- treewalk.free_flat(flat)- }- }- i++- }- return out-}--type CanonTarget = {- map_index: mut usize- target: mut bytes.Bytes-}--fn canonical_targets(- path: bytes.Bytes,- maps: list[ref rename.RenameMap]-) list[ref CanonTarget] = trust {- val out: mut list[ref CanonTarget] = lists.new[ref CanonTarget]()- val i: mut usize = 0- for i < @len(maps) {- val m = @get(maps, i)- if m is some mm {- if mm != none {- val t = rename.lookup(mm, path)- if t is some dest {- val exists: mut bool = false- for c in out {- if bytes.Bytes.eql(c.target, dest) {- exists = true- }- }- if !exists {- val c: mut ref CanonTarget = @alloc(@sizeof(CanonTarget)) as ref CanonTarget- c.map_index = i- c.target = bytes.Bytes.dup(dest)- @append(out, c)- }- }- }- }- i++- }- return out-}--fn free_canon(xs: list[ref CanonTarget]) void = trust {- for c in xs {- val tp: mut ref void = c.target.ptr as ref void- @free(tp)- val cp: mut ref void = c as ref void- @free(cp)- }- @listfree(xs)-}--fn canonical_path(targets: list[ref CanonTarget], path: bytes.Bytes) bytes.Bytes = trust {- if @len(targets) == 1 {- val o = @get(targets, 0)- if o is some c {- return c.target- }- }- return path-}--fn add_value(- adds: mut list[ref conflict.ConflictValue],- removes: mut list[ref conflict.ConflictValue],- t: EntryTerm-) void = trust {- if t.present {- val v: ref conflict.ConflictValue = conflict.value(t.kind, t.target)- if t.positive {- @append(adds, v)- } else {- @append(removes, v)- }- } else {- val v2: ref conflict.ConflictValue = conflict.value_absent()- if t.positive {- @append(adds, v2)- } else {- @append(removes, v2)- }- }-}--fn all_files(- adds: list[ref conflict.ConflictValue],- removes: list[ref conflict.ConflictValue]-) bool = trust {- for v in adds {- if v.kind != tree.KIND_FILE && v.kind != tree.KIND_EXECUTABLE {- if v.kind != 0 {- return false- }- }- }- for v in removes {- if v.kind != tree.KIND_FILE && v.kind != tree.KIND_EXECUTABLE {- if v.kind != 0 {- return false- }- }- }- return true-}--fn mode_of(kind: u8) bool = {- return kind == tree.KIND_EXECUTABLE-}--/// Merge the executable bit for a two-add/one-remove sum. Returns -1 when the-/// mode is unresolved, 0 for regular, and 1 for executable.-fn merge_mode(- adds: list[ref conflict.ConflictValue],- removes: list[ref conflict.ConflictValue]-) i32 = trust {- if @len(adds) != 2 || @len(removes) != 1 {- return -1- }- val a0 = @get(adds, 0)- val a1 = @get(adds, 1)- val r0 = @get(removes, 0)- val ma0: mut i32 = -1- val ma1: mut i32 = -1- val mr: mut i32 = -1- if a0 is some x {- if x.kind != 0 {- ma0 = 0- if mode_of(x.kind) {- ma0 = 1- }- }- }- if a1 is some y {- if y.kind != 0 {- ma1 = 0- if mode_of(y.kind) {- ma1 = 1- }- }- }- if r0 is some z {- if z.kind != 0 {- mr = 0- if mode_of(z.kind) {- mr = 1- }- }- }- if ma0 < 0 || ma1 < 0 {- return -1- }- if ma0 == ma1 {- return ma0- }- if mr >= 0 && ma0 == mr {- return ma1- }- if mr >= 0 && ma1 == mr {- return ma0- }- return -1-}--fn make_conflict_entry(- repo: layout.Repo,- tx: mut ref txnmod.Txn,- path: bytes.Bytes,- sum: algebra.Sum,- rerere: mut list[usize]-) option[ref OutEntry] = trust {- val body: bytes.Bytes = algebra.conflict_body(sum)- // Resolution memory applies only to file-valued conflicts.- if all_files(sum.adds, sum.removes) {- val memo = resolutions.lookup(repo, body)- if memo is some blob {- val e: ref OutEntry = new_out(path, tree.KIND_FILE, blob)- algebra.free_sum(sum)- val bp: mut ref void = body.ptr as ref void- @free(bp)- val lb: mut ref void = blob.ptr as ref void- @free(lb)- @append(rerere, 1)- return some e- }- }- val id: objid.Id = txnmod.add_object(tx, types.CONFLICT, body)- algebra.free_sum(sum)- return some new_out(path, tree.KIND_CONFLICT, id)-}--fn term_positive(terms: list[ref TreeTerm], i: usize) bool = trust {- val o = @get(terms, i)- if o is some t {- return t.positive- }- return true-}--fn merge_entry(- repo: layout.Repo,- tx: mut ref txnmod.Txn,- handles: list[ref store.Handle],- git: ref object.GitRepo,- has_git: bool,- path: bytes.Bytes,- terms: list[EntryTerm],- adjacent_merge: bool,- rerere: mut list[usize]-) option[ref OutEntry] = trust {- val adds: mut list[ref conflict.ConflictValue] = lists.new[ref conflict.ConflictValue]()- val removes: mut list[ref conflict.ConflictValue] = lists.new[ref conflict.ConflictValue]()- for t in terms {- add_value(adds, removes, t)- }- val sum: algebra.Sum = algebra.simplify_tx(handles, adds, removes, tx)- val resolved = algebra.resolved(sum)- if resolved is some v {- val kind: u8 = v.kind- val target: objid.Id = v.target- val out: mut option[ref OutEntry] = none- if kind != 0 {- out = some new_out(path, kind, target)- }- algebra.free_sum(sum)- return out- }- // Try a content merge for a simple three-term file conflict.- if all_files(sum.adds, sum.removes) && @len(sum.adds) == 2 && @len(sum.removes) == 1 {- val a0 = @get(sum.adds, 0)- val a1 = @get(sum.adds, 1)- val r0 = @get(sum.removes, 0)- val success: mut bool = true- val base_id: mut objid.Id = objid.id_none()- val ours_id: mut objid.Id = objid.id_none()- val theirs_id: mut objid.Id = objid.id_none()- val ours_kind: mut u8 = tree.KIND_FILE- if a0 is some x {- if x.kind != 0 {- ours_id = x.target- ours_kind = x.kind- } else {- success = false- }- }- if a1 is some y {- if y.kind != 0 {- theirs_id = y.target- } else {- success = false- }- }- if r0 is some z {- if z.kind != 0 {- base_id = z.target- } else {- success = false- }- }- if success && !attributes.merge_binary(repo, path) {- val merged = filemerge.merge_blobs_tx(- handles,- git,- has_git,- base_id,- ours_id,- theirs_id,- adjacent_merge,- tx- )- if merged is some m {- if !m.conflicted {- val lines: list[bytes.Bytes] = filemerge.split_lines(m.data)- val blob_id: objid.Id = filemerge.add_blob(tx, lines)- @listfree(lines)- val mode: i32 = merge_mode(sum.adds, sum.removes)- if mode >= 0 {- val kind: mut u8 = tree.KIND_FILE- if mode == 1 {- kind = tree.KIND_EXECUTABLE- }- filemerge.free_edit(m)- algebra.free_sum(sum)- return some new_out(path, kind, blob_id)- }- free_id(blob_id)- }- filemerge.free_edit(m)- }- }- }- return make_conflict_entry(repo, tx, path, sum, rerere)-}--fn collect_paths(canon: list[ref OrigEntry]) list[bytes.Bytes] = trust {- val out: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()- for e in canon {- if !list_has_path(out, e.path) {- @append(out, e.path)- }- }- sort_paths(out)- return out-}--fn has_children(canon: list[ref OrigEntry], term: usize, path: bytes.Bytes) bool = trust {- for e in canon {- if e.term == term && has_prefix(e.path, path) {- return true- }- }- return false-}--fn exact_entry(- canon: list[ref OrigEntry],- term: usize,- path: bytes.Bytes-) option[ref OrigEntry] = trust {- for e in canon {- if e.term == term && bytes.Bytes.eql(e.path, path) {- return some e- }- }- return none-}--/// Merge signed tree terms. `maps[i]` is the rename map for term `i` (or none).-pub fn merge(- repo: layout.Repo,- tx: mut ref txnmod.Txn,- handles: list[ref store.Handle],- git: ref object.GitRepo,- has_git: bool,- terms: list[ref TreeTerm],- maps: list[ref rename.RenameMap],- adjacent_merge: bool-) Outcome = trust {- val orig: list[ref OrigEntry] = make_terms(handles, terms, tx)- val canon: mut list[ref OrigEntry] = lists.new[ref OrigEntry]()- val special: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()- val consumed: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()- for e in orig {- val targets: list[ref CanonTarget] = canonical_targets(e.path, maps)- if @len(targets) > 1 {- // Both sides renamed this base path to different destinations.- if !list_has_path(special, e.path) {- @append(special, bytes.Bytes.dup(e.path))- }- }- val cp: bytes.Bytes = canonical_path(targets, e.path)- @append(canon, new_orig(e.term, cp, e.kind, e.target))- free_canon(targets)- }-- val out: mut list[ref OutEntry] = lists.new[ref OutEntry]()- val rerere: mut list[usize] = lists.new[usize]()-- // Both-sides-renamed-differently conflicts are materialized at the original- // base path with the destinations as terms.- for sp in special {- val targets: list[ref CanonTarget] = canonical_targets(sp, maps)- val ets: mut list[EntryTerm] = lists.new[EntryTerm]()- for c in targets {- val found = find_orig(orig, c.map_index, c.target)- val term: mut EntryTerm = EntryTerm{- positive: true,- present: false,- kind: 0,- target: objid.id(none)- }- if found is some fe {- term.present = true- term.kind = fe.kind- term.target = fe.target- }- @append(ets, term)- if !list_has_path(consumed, c.target) {- @append(consumed, bytes.Bytes.dup(c.target))- }- }- // The base term is the first negative term.- val base_term: mut i32 = -1- val ti: mut usize = 0- for ti < @len(terms) {- val to = @get(terms, ti)- if to is some tt {- if !tt.positive {- base_term = ti as i32- break- }- }- ti++- }- if base_term >= 0 {- val found_base = find_orig(orig, base_term as usize, sp)- val bt: mut EntryTerm = EntryTerm{- positive: false,- present: false,- kind: 0,- target: objid.id(none)- }- if found_base is some bf {- bt.present = true- bt.kind = bf.kind- bt.target = bf.target- }- @append(ets, bt)- }- val merged = merge_entry(repo, tx, handles, git, has_git, sp, ets, adjacent_merge, rerere)- if merged is some me {- @append(out, me)- }- free_canon(targets)- @listfree(ets)- if !list_has_path(consumed, sp) {- @append(consumed, bytes.Bytes.dup(sp))- }- }-- val paths: list[bytes.Bytes] = collect_paths(canon)- for path in paths {- if list_has_path(consumed, path) {- continue- }- val any_exact: mut bool = false- val any_children: mut bool = false- val ti: mut usize = 0- for ti < @len(terms) {- if exact_entry(canon, ti, path) is some _ {- any_exact = true- }- if has_children(canon, ti, path) {- any_children = true- }- ti++- }- if !any_exact {- continue- }- val mixed: bool = any_children- val ets: mut list[EntryTerm] = lists.new[EntryTerm]()- val k: mut usize = 0- for k < @len(terms) {- val exact = exact_entry(canon, k, path)- if exact is some ee {- @append(- ets,- EntryTerm{- positive: term_positive(terms, k),- present: true,- kind: ee.kind,- target: ee.target- }- )- } elif mixed && has_children(canon, k, path) {- val sub: objid.Id = build_subtree(tx, canon, k, path)- @append(- ets,- EntryTerm{- positive: term_positive(terms, k),- present: true,- kind: tree.KIND_SUBTREE,- target: sub- }- )- } else {- @append(- ets,- EntryTerm{- positive: term_positive(terms, k),- present: false,- kind: 0,- target: objid.id(none)- }- )- }- k++- }- val merged = merge_entry(repo, tx, handles, git, has_git, path, ets, adjacent_merge, rerere)- if merged is some me {- @append(out, me)- }- @listfree(ets)- if mixed {- // Children were folded into the merged subtree at `path`.- for e in canon {- if has_prefix(e.path, path) {- if !list_has_path(consumed, e.path) {- @append(consumed, bytes.Bytes.dup(e.path))- }- }- }- }- }-- val tree_id: objid.Id = build_from_entries(tx, out)- free_out(out)- free_orig(canon)- free_orig(orig)- @listfree(paths)- @listfree(special)- @listfree(consumed)- val applied: usize = @len(rerere)- @listfree(rerere)- return Outcome{tree: tree_id, rerere: applied}-}--- a/veins/src/net/stream.sx+++ /dev/null@@ -1,203 +0,0 @@-/// Reliable byte streams over a plain fd, TLS, stdio, or a child process.--val bytes = use("../core/bytes.sx")-val tls = use("../crypto/tls.sx")-val native = use("../io/native.sx")--extern (C) fn c_pipe(fds: ref i32) i32 = "pipe"-extern (C) fn c_fork() i32 = "fork"-extern (C) fn c_dup2(oldfd: i32, newfd: i32) i32 = "dup2"-extern (C) fn c_execl(path: ref u8, arg0: ref u8, ...) i32 = "execl"-extern (C) fn c_waitpid(pid: i32, status: ref i32, options: i32) i32 = "waitpid"-extern (C) fn c_close(fd: i32) i32 = "close"-extern (C) fn c__exit(code: i32) void = "_exit"-extern (C) fn c_readlink(path: ref u8, buf: ref u8, cap: usize) i64 = "readlink"--pub val K_FD: u8 = 0-pub val K_TLS: u8 = 1-pub val K_STDIO: u8 = 2-pub val K_PROC: u8 = 3--pub type Stream = {- kind: mut u8- fd_in: mut i32- fd_out: mut i32- ssl: mut ref void- pid: mut i32-}--pub fn stdio_stream() Stream = {- return Stream{kind: K_STDIO, fd_in: 0, fd_out: 1, ssl: none, pid: 0}-}--pub fn fd_stream(fd: i32) Stream = {- return Stream{kind: K_FD, fd_in: fd, fd_out: fd, ssl: none, pid: 0}-}--pub fn tls_stream(fd: i32, ssl: ref void) Stream = {- return Stream{kind: K_TLS, fd_in: fd, fd_out: fd, ssl: ssl, pid: 0}-}--fn close_fd(fd: i32) void = trust {- if fd > 2 {- c_close(fd)- }-}--pub fn close(s: Stream) void = trust {- if s.kind == K_TLS && s.ssl != none {- tls.free(s.ssl)- }- if s.kind == K_PROC {- close_fd(s.fd_in)- close_fd(s.fd_out)- if s.pid > 0 {- val status: mut i32 = 0- c_waitpid(s.pid, @addr(status), 0)- }- } elif s.kind == K_FD {- close_fd(s.fd_in)- }-}--/// Read up to `n` bytes. Returns 0 at end of stream, -1 on error.-pub fn read(s: Stream, buf: ref u8, n: usize) i64 = trust {- if n == 0 {- return 0- }- if s.kind == K_TLS {- return tls.read(s.ssl, buf, n)- }- val fd: mut i32 = s.fd_in- if s.kind == K_STDIO {- fd = 0- }- return native.read_fd(fd, buf, n)-}--pub fn write_all(s: Stream, data: bytes.Bytes) bool = trust {- if s.kind == K_STDIO {- return native.write_fd_all(1, data)- }- if s.kind == K_TLS {- val off: mut usize = 0- for off < data.len {- val n: i64 = tls.write(- s.ssl,- @ptradd(data.ptr, off as i64) as ref u8,- data.len - off- )- if n <= 0 {- return false- }- off = off + n as usize- }- return true- }- return native.write_fd_all(s.fd_out, data)-}--pub fn write_bytes(s: Stream, ptr: ref u8, n: usize) bool = trust {- return write_all(s, bytes.bytes(ptr, n))-}--type PipePair = {- read_fd: mut i32- write_fd: mut i32- valid: mut bool-}--fn pipe_pair() PipePair = trust {- val fds: ref i32 = @alloc(8) as ref i32- val rc: i32 = c_pipe(fds)- if rc != 0 {- @free(fds as ref void)- return PipePair{read_fd: -1, write_fd: -1, valid: false}- }- val a: i32 = @load32(fds)- val b: i32 = @load32(@ptradd(fds, 4) as ref i32)- @free(fds as ref void)- return PipePair{read_fd: a, write_fd: b, valid: true}-}--/// Start `/bin/sh -c <command>` with pipes on stdin and stdout.-pub fn spawn(command: bytes.Bytes) option[Stream] = trust {- val ip: PipePair = pipe_pair()- val op: PipePair = pipe_pair()- if !ip.valid || !op.valid {- return none- }- val cmd_z: ref u8 = bytes.Bytes.to_cstr(command)- val pid: i32 = c_fork()- if pid == 0 {- val rc1: i32 = c_dup2(ip.read_fd, 0)- val rc2: i32 = c_dup2(op.write_fd, 1)- close_fd(ip.read_fd)- close_fd(ip.write_fd)- close_fd(op.read_fd)- close_fd(op.write_fd)- val rc3: i32 = c_execl(c"/bin/sh", c"sh", c"-c", cmd_z, none)- if rc1 == 0 && rc2 == 0 && rc3 == 0 {- c__exit(0)- }- c__exit(127)- }- @free(cmd_z as ref void)- close_fd(ip.read_fd)- close_fd(op.write_fd)- if pid < 0 {- close_fd(op.read_fd)- close_fd(ip.write_fd)- return none- }- val s: Stream = Stream{- kind: K_PROC,- fd_in: op.read_fd,- fd_out: ip.write_fd,- ssl: none,- pid: pid- }- return some s-}--/// Return a single-quoted shell word. The result is owned by the caller.-pub fn quote(word: bytes.Bytes) bytes.Bytes = trust {- val quote: u8 = 39- val joined: ref u8 = @alloc(word.len * 4 + 4) as ref u8- val mut_len: mut usize = 0- @store8(@ptradd(joined, mut_len as i64), quote)- mut_len++- val i: mut usize = 0- for i < word.len {- val c: u8 = bytes.Bytes.at(word, i)- if c == quote {- @store8(@ptradd(joined, mut_len as i64), quote)- mut_len++- @store8(@ptradd(joined, mut_len as i64), 92)- mut_len++- @store8(@ptradd(joined, mut_len as i64), quote)- mut_len++- @store8(@ptradd(joined, mut_len as i64), quote)- mut_len++- } else {- @store8(@ptradd(joined, mut_len as i64), c)- mut_len++- }- i++- }- @store8(@ptradd(joined, mut_len as i64), quote)- mut_len++- return bytes.bytes(joined, mut_len)-}--/// Resolve the running executable, for spawning a local stdio server.-pub fn self_exe() bytes.Bytes = trust {- val buf: ref u8 = @alloc(4096) as ref u8- val n: i64 = c_readlink(c"/proc/self/exe", buf, 4095)- if n > 0 {- @store8(@ptradd(buf, n), 0)- return bytes.bytes(buf, n as usize)- }- @free(buf as ref void)- return bytes.Bytes.dup(bytes.bytes(c"vn", 2))-}--- a/veins/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/veins/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/veins/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/veins/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/veins/src/object/content.sx+++ /dev/null@@ -1,161 +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")-val txnmod = use("../store/txn.sx")-val promisor = use("../protocol/promisor.sx")--fn read_body_any(- handles: list[ref store.Handle],- id: objid.Id,- expected: u8,- use_cache: bool,- tx: ref txnmod.Txn-) option[bytes.Bytes] = trust {- if use_cache {- val cached = txnmod.find_cached(tx, expected, id)- if cached is some b {- return some bytes.Bytes.dup(b)- }- }- return state.read_body(handles, id, expected)-}--fn append_blob(- handles: list[ref store.Handle],- out: mut buf.Buf,- id: objid.Id,- depth: usize,- git: object.GitRepo,- has_git: bool,- use_cache: bool,- tx: ref txnmod.Txn-) 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 = read_body_any(handles, id, types.BLOB, use_cache, tx)- 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 = read_body_any(handles, e.id, types.CHUNK, use_cache, tx)- val chunk2: mut option[bytes.Bytes] = chunk_opt- if chunk2 is none {- promisor.ensure(handles)- if promisor.is_active() {- chunk2 = promisor.fetch_chunk(e.id)- }- }- match chunk2 {- 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, use_cache, tx) {- 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.-fn read_blob_inner(- handles: list[ref store.Handle],- id: objid.Id,- git: object.GitRepo,- has_git: bool,- use_cache: bool,- tx: ref txnmod.Txn-) option[bytes.Bytes] = trust {- val out: mut buf.Buf = buf.new(4096)- val good: bool = append_blob(handles, out, id, 0, git, has_git, use_cache, tx)- val result: mut option[bytes.Bytes] = none- if good {- result = some(bytes.Bytes.dup(buf.Buf.view(out)))- }- buf.Buf.free(out)- return result-}--pub fn read_blob(- handles: list[ref store.Handle],- id: objid.Id,- git: object.GitRepo,- has_git: bool-) option[bytes.Bytes] = trust {- return read_blob_inner(handles, id, git, has_git, false, none)-}--pub fn read_blob_tx(- handles: list[ref store.Handle],- id: objid.Id,- git: object.GitRepo,- has_git: bool,- tx: ref txnmod.Txn-) option[bytes.Bytes] = trust {- return read_blob_inner(handles, id, git, has_git, true, tx)-}--- a/veins/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/veins/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/veins/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/veins/src/object/operation.sx+++ /dev/null@@ -1,122 +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]- owned: mut bytes.Bytes-}--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.owned = bytes.empty()- 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)- if op.owned.ptr != none {- val ob: mut ref void = op.owned.ptr as ref void- trust @free(ob)- }- val p2: mut ref void = op as ref void- trust @free(p2)-}--- a/veins/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/veins/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/veins/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/veins/src/object/treewalk.sx+++ /dev/null@@ -1,345 +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")-val txnmod = use("../store/txn.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)-}--fn read_tree_inner(- handles: list[ref store.Handle],- id: objid.Id,- use_cache: bool,- tx: ref txnmod.Txn-) option[ref tree.Tree] = trust {- val body_opt: mut option[bytes.Bytes] = read.read_body(handles, id, types.TREE)- if use_cache {- val cached = txnmod.find_cached(tx, types.TREE, id)- if cached is some cb {- val owned: bytes.Bytes = bytes.Bytes.dup(cb)- if body_opt is some old {- files.free_buffer(old)- }- body_opt = some owned- }- }- 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 read_tree(handles: list[ref store.Handle], id: objid.Id) option[ref tree.Tree] = trust {- return read_tree_inner(handles, id, false, none)-}--pub fn read_tree_tx(- handles: list[ref store.Handle],- id: objid.Id,- tx: ref txnmod.Txn-) option[ref tree.Tree] = trust {- return read_tree_inner(handles, id, true, tx)-}--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,- use_cache: bool,- tx: ref txnmod.Txn-) bool = trust {- if depth > 4096 {- return false- }- val t_opt = read_tree_inner(handles, tree_id, use_cache, tx)- 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, use_cache, tx) {- 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.-fn flatten_inner(- handles: list[ref store.Handle],- tree_id: objid.Id,- use_cache: bool,- tx: ref txnmod.Txn-) list[ref FlatEntry] = trust {- val out: mut list[ref FlatEntry] = lists.new[ref FlatEntry]()- if !flatten_into(handles, tree_id, bytes.empty(), out, 0, use_cache, tx) {- // 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(handles: list[ref store.Handle], tree_id: objid.Id) list[ref FlatEntry] = trust {- return flatten_inner(handles, tree_id, false, none)-}--pub fn flatten_tx(- handles: list[ref store.Handle],- tree_id: objid.Id,- tx: ref txnmod.Txn-) list[ref FlatEntry] = trust {- return flatten_inner(handles, tree_id, true, tx)-}--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 flatten_or_empty_tx(- handles: list[ref store.Handle],- tree: option[objid.Id],- tx: ref txnmod.Txn-) list[ref FlatEntry] = trust {- if tree is some id {- return flatten_tx(handles, id, tx)- }- 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/veins/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/veins/src/object/view.sx+++ /dev/null@@ -1,409 +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]- owned: mut bytes.Bytes-}--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.owned = bytes.empty()- 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)- if v.owned.ptr != none {- val ob: mut ref void = v.owned.ptr as ref void- trust @free(ob)- }- val p2: mut ref void = v as ref void- trust @free(p2)-}--- a/veins/src/protocol/client.sx+++ /dev/null@@ -1,1112 +0,0 @@-val time = use("std/time")-val bytes = use("../core/bytes.sx")-val buf = use("../core/buf.sx")-val lists = use("../core/lists.sx")-val reader = use("../core/reader.sx")-val objid = use("../object/id.sx")-val store = use("../store/store.sx")-val state = use("../store/state.sx")-val layout = use("../store/layout.sx")-val writer = use("../store/writer.sx")-val zstd = use("../store/zstd.sx")-val stream = use("../net/stream.sx")-val wire = use("../protocol/wire.sx")-val msg = use("../protocol/messages.sx")-val ed = use("../crypto/ed25519.sx")-val tls = use("../crypto/tls.sx")-val keys = use("../auth/keys.sx")-val handshake = use("../auth/handshake.sx")-val b3 = use("../crypto/blake3.sx")-val random = use("std/crypto/random")--pub type Client = {- s: mut stream.Stream- binding: mut bytes.Bytes- version: mut u16- role: mut u8- authed: mut bool- fingerprint: mut bytes.Bytes- repo_name: mut bytes.Bytes- last_error: mut bytes.Bytes-}--pub type WhoAmI = {- role: mut u8- fingerprint: mut bytes.Bytes-}--val connect_error: mut bytes.Bytes = @zeroed--fn set_connect_error(text: ref u8) void = trust {- if connect_error.ptr != none {- bytes.free_ptr(connect_error.ptr)- }- connect_error = bytes.Bytes.dup(bytes.from_cstr(text))-}--fn clear_connect_error() void = trust {- if connect_error.ptr != none {- bytes.free_ptr(connect_error.ptr)- }- connect_error = bytes.empty()-}--pub fn last_connect_error() bytes.Bytes = trust {- if connect_error.ptr == none {- return bytes.empty()- }- return bytes.Bytes.dup(connect_error)-}--type Url = {- tls: mut bool- host: mut bytes.Bytes- port: mut i32- path: mut bytes.Bytes- ssh: mut bool-}--type Authority = {- host: mut bytes.Bytes- port: mut i32-}--type IncomingRecord = {- id: mut bytes.Bytes- kind: mut u8- body: mut bytes.Bytes-}--fn copy_bytes(b: bytes.Bytes) bytes.Bytes = trust {- return bytes.Bytes.dup(b)-}--fn parse_port(text: bytes.Bytes) option[i32] = trust {- if text.len == 0 {- return none- }- val port: mut i32 = 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- }- port = port * 10 + (c - 48) as i32- i++- }- return some port-}--fn find_char(b: bytes.Bytes, needle: u8) i64 = trust {- val i: mut usize = 0- for i < b.len {- if bytes.Bytes.at(b, i) == needle {- return i as i64- }- i++- }- return -1-}--fn parse_authority(- authority: bytes.Bytes,- default_port: i32,- strip_user: bool-) Authority = trust {- val hp: mut bytes.Bytes = authority- if strip_user {- val at: i64 = find_char(authority, 64)- if at >= 0 {- hp = bytes.Bytes.slice(authority, (at as usize) + 1, authority.len)- }- }- val colon: i64 = find_char(hp, 58)- val host: mut bytes.Bytes = hp- val port: mut i32 = default_port- if colon >= 0 {- host = bytes.Bytes.slice(hp, 0, colon as usize)- val po = parse_port(bytes.Bytes.slice(hp, (colon as usize) + 1, hp.len))- if po is some p {- port = p- }- }- return Authority{host: bytes.Bytes.dup(host), port: port}-}--pub fn parse_url(url: bytes.Bytes) option[Url] = trust {- if bytes.Bytes.starts_with(url, bytes.bytes(c"file://", 7)) {- return some Url{- tls: false,- host: bytes.empty(),- port: 0,- path: bytes.Bytes.dup(bytes.Bytes.slice(url, 7, url.len)),- ssh: false- }- }- if bytes.Bytes.starts_with(url, bytes.bytes(c"ssh://", 6)) {- val rest: bytes.Bytes = bytes.Bytes.slice(url, 6, url.len)- val slash: i64 = find_char(rest, 47)- if slash < 0 {- return none- }- val auth: bytes.Bytes = bytes.Bytes.slice(rest, 0, slash as usize)- val path: bytes.Bytes = bytes.Bytes.slice(rest, (slash as usize) + 1, rest.len)- val parsed = parse_authority(auth, 22, true)- return some Url{- tls: false,- host: parsed.host,- port: parsed.port,- path: bytes.Bytes.dup(path),- ssh: true- }- }- if bytes.Bytes.starts_with(url, bytes.bytes(c"veins://", 8)) {- val rest: bytes.Bytes = bytes.Bytes.slice(url, 8, url.len)- val slash: i64 = find_char(rest, 47)- if slash < 0 {- return none- }- val auth: bytes.Bytes = bytes.Bytes.slice(rest, 0, slash as usize)- val path: bytes.Bytes = bytes.Bytes.slice(rest, (slash as usize) + 1, rest.len)- val parsed = parse_authority(auth, 7419, false)- return some Url{- tls: true,- host: parsed.host,- port: parsed.port,- path: bytes.Bytes.dup(path),- ssh: false- }- }- return none-}--fn build_command(parts: list[bytes.Bytes]) bytes.Bytes = trust {- val out: mut buf.Buf = buf.new(128)- for p in parts {- if out.len > 0 {- buf.Buf.put_u8(out, 32)- }- val q: bytes.Bytes = stream.quote(p)- buf.Buf.put_bytes(out, q)- bytes.free_owned(q)- }- val r: bytes.Bytes = bytes.Bytes.dup(buf.Buf.view(out))- buf.Buf.free(out)- return r-}--fn connect_stream(u: Url, tls_pin: bytes.Bytes) option[stream.Stream] = trust {- if u.ssh {- val parts: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()- @append(parts, copy_bytes(bytes.bytes(c"ssh", 3)))- if u.port != 22 {- @append(parts, copy_bytes(bytes.bytes(c"-p", 2)))- val ps: ref u8 = @fmtalloc("{d}", {u.port})- @append(parts, bytes.from_cstr(ps))- @free(ps as ref void)- }- val host_z: ref u8 = bytes.Bytes.to_cstr(u.host)- @append(parts, copy_bytes(bytes.from_cstr(host_z)))- @free(host_z as ref void)- @append(parts, copy_bytes(bytes.bytes(c"vn", 2)))- @append(parts, copy_bytes(bytes.bytes(c"serve", 5)))- @append(parts, copy_bytes(bytes.bytes(c"-stdio", 6)))- @append(parts, copy_bytes(u.path))- val cmd: bytes.Bytes = build_command(parts)- free_parts(parts)- val res = stream.spawn(cmd)- bytes.free_owned(cmd)- if res is none {- set_connect_error(c"cannot start the SSH transport")- }- return res- }- if u.tls {- val host_z2: ref u8 = bytes.Bytes.to_cstr(u.host)- val fd: i32 = tls.tcp_connect(host_z2, u.port)- if fd < 0 {- @free(host_z2 as ref void)- set_connect_error(c"cannot connect: host refused the connection or is unreachable")- return none- }- val ctx: mut ref void = tls.client_ctx()- if tls_pin.len > 0 {- ctx = tls.client_ctx_pinned()- }- if ctx == none {- @free(host_z2 as ref void)- native_close(fd)- set_connect_error(c"cannot initialize TLS")- return none- }- val ssl: ref void = tls.connect(ctx, fd, host_z2)- tls.free_ctx(ctx)- @free(host_z2 as ref void)- if ssl == none {- native_close(fd)- set_connect_error(c"TLS handshake failed")- return none- }- return some stream.tls_stream(fd, ssl)- }- val exe: bytes.Bytes = stream.self_exe()- val parts2: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()- @append(parts2, exe)- @append(parts2, copy_bytes(bytes.bytes(c"serve", 5)))- @append(parts2, copy_bytes(bytes.bytes(c"-stdio", 6)))- @append(parts2, copy_bytes(u.path))- val cmd2: bytes.Bytes = build_command(parts2)- free_parts(parts2)- val res2 = stream.spawn(cmd2)- bytes.free_owned(cmd2)- if res2 is none {- set_connect_error(c"cannot start the local vn server")- }- return res2-}--fn free_parts(parts: list[bytes.Bytes]) void = trust {- for p in parts {- if p.ptr != none {- bytes.free_owned(p)- }- }- @listfree(parts)-}--extern (C) fn close(fd: i32) i32 = "close"--fn native_close(fd: i32) void = trust {- close(fd)-}--fn free_hello_fields(h: msg.Hello) void = trust {- msg.free_hello(h)-}--/// Connect and authenticate. Empty key name means anonymous unless required.-pub fn connect(- url: bytes.Bytes,- key_name: bytes.Bytes,- repo_name: bytes.Bytes-) option[Client] = trust {- return connect_pinned(url, key_name, repo_name, bytes.empty())-}--pub fn connect_pinned(- url: bytes.Bytes,- key_name: bytes.Bytes,- repo_name: bytes.Bytes,- tls_pin: bytes.Bytes-) option[Client] = trust {- clear_connect_error()- val u_opt = parse_url(url)- val u: mut Url = Url{- tls: false,- host: bytes.empty(),- port: 0,- path: bytes.empty(),- ssh: false- }- match u_opt {- some v => {- u = v- }- none => {- set_connect_error(c"invalid remote URL")- return none- }- }- val st_opt = connect_stream(u, tls_pin)- if u.host.ptr != none {- bytes.free_ptr(u.host.ptr)- }- if u.path.ptr != none {- bytes.free_ptr(u.path.ptr)- }- val st: mut stream.Stream = stream.stdio_stream()- match st_opt {- some v => {- st = v- }- none => {- return none- }- }- val binding: mut bytes.Bytes = bytes.empty()- if st.kind == stream.K_TLS {- val b: ref u8 = @alloc(32) as ref u8- if tls.exporter(st.ssl, b, 32) {- binding = bytes.bytes(b, 32)- } else {- @free(b as ref void)- }- if tls_pin.len > 0 {- val digest: ref u8 = @alloc(32) as ref u8- val got: bool = tls.peer_sha256(st.ssl, digest)- val hex: bytes.Bytes = tls.to_hex(bytes.bytes(digest, 32))- val matched: bool = got && tls.hex_equal(hex, tls_pin)- bytes.free_ptr(hex.ptr)- bytes.free_ptr(digest)- if !matched {- stream.close(st)- if binding.ptr != none {- @free(binding.ptr as ref void)- }- set_connect_error(c"TLS certificate pin mismatch")- return none- }- }- }- val cn: ref u8 = @alloc(32) as ref u8- random.random_bytes(cn as ref void, 32)- val client_nonce: bytes.Bytes = bytes.Bytes.dup(bytes.bytes(cn, 32))- @free(cn as ref void)- val caps: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()- @append(caps, copy_bytes(bytes.bytes(c"zstd-records", 12)))- @append(caps, copy_bytes(bytes.bytes(c"lazy-chunks", 11)))- @append(caps, copy_bytes(bytes.bytes(c"push", 4)))- @append(caps, copy_bytes(bytes.bytes(c"auth-ed25519", 12)))- val hello: msg.Hello = msg.Hello{- min_version: msg.PROTOCOL_VERSION,- max_version: msg.PROTOCOL_VERSION,- capabilities: caps,- repo: bytes.Bytes.dup(repo_name),- client_nonce: bytes.Bytes.dup(client_nonce)- }- val hello_body: bytes.Bytes = msg.encode_hello(hello)- free_hello_fields(hello)- if !wire.write_frame(st, wire.HELLO, 1, hello_body) {- stream.close(st)- bytes.free_owned(client_nonce)- if binding.ptr != none {- bytes.free_owned(binding)- }- set_connect_error(c"connection closed during the protocol handshake")- return none- }- val f_opt = wire.read_frame(st)- val f: mut wire.Frame = wire.Frame{- kind: 0,- request_id: 0,- payload: bytes.empty(),- base: bytes.empty()- }- match f_opt {- some x => {- f = x- }- none => {- stream.close(st)- bytes.free_owned(client_nonce)- if binding.ptr != none {- bytes.free_owned(binding)- }- set_connect_error(c"server closed the connection during the protocol handshake")- return none- }- }- if f.kind != wire.HELLO_OK {- wire.free_frame(f)- stream.close(st)- bytes.free_owned(client_nonce)- if binding.ptr != none {- bytes.free_owned(binding)- }- set_connect_error(c"server rejected the protocol handshake")- return none- }- val hd = msg.decode_hello_ok(f.payload)- val hok: mut msg.HelloOk = msg.HelloOk{- version: 0,- capabilities: lists.new[bytes.Bytes](),- server_nonce: bytes.empty(),- auth_required: 0- }- val parsed_ok: mut bool = false- match hd {- ok v => {- hok = v- parsed_ok = true- }- err _ => {- }- }- wire.free_frame(f)- if !parsed_ok {- stream.close(st)- bytes.free_owned(client_nonce)- if binding.ptr != none {- bytes.free_owned(binding)- }- set_connect_error(c"server sent an invalid protocol handshake")- return none- }- val key_sel: mut bytes.Bytes = key_name- if key_sel.len == 0 && hok.auth_required != 0 {- key_sel = bytes.bytes(c"default", 7)- }- val c: mut ref Client = @alloc(@sizeof(Client)) as ref Client- c.s = st- c.binding = binding- c.version = hok.version- c.role = 0- c.authed = false- c.fingerprint = bytes.empty()- c.repo_name = bytes.Bytes.dup(repo_name)- c.last_error = bytes.empty()- if key_sel.len > 0 {- val key_opt = keys.load(key_sel)- if key_opt is some key {- val message: bytes.Bytes = handshake.auth_message(- hok.version,- repo_name,- hok.server_nonce,- client_nonce,- binding- )- val sig_opt = ed.sign(key.seed, message)- bytes.free_owned(message)- if sig_opt is some sig {- val a: msg.Auth = msg.Auth{- public_key: bytes.Bytes.dup(key.public_key),- signature: bytes.Bytes.dup(sig)- }- val ab: bytes.Bytes = msg.encode_auth(a)- bytes.free_ptr(a.public_key.ptr)- bytes.free_ptr(a.signature.ptr)- bytes.free_owned(sig)- wire.write_frame(st, wire.AUTH, 2, ab)- val af = wire.read_frame(st)- if af is some afr {- if afr.kind == wire.AUTH_OK {- val ad = msg.decode_auth_ok(afr.payload)- if ad is ok aok {- c.role = aok.role- c.authed = true- c.fingerprint = bytes.Bytes.dup(aok.fingerprint)- if aok.fingerprint.ptr != none {- bytes.free_ptr(aok.fingerprint.ptr)- }- }- }- wire.free_frame(afr)- }- }- keys.free_key(key)- }- }- val auth_req: bool = hok.auth_required != 0- msg.free_hello_ok(hok)- bytes.free_owned(client_nonce)- if auth_req && !c.authed {- if key_sel.len == 0 {- set_connect_error(c"authentication required but no key is configured")- } else {- set_connect_error(c"authentication failed: the key is missing or not authorized")- }- free_client(c)- return none- }- clear_connect_error()- return some c-}--pub fn free_client(c: mut ref Client) void = trust {- stream.close(c.s)- if c.binding.ptr != none {- bytes.free_ptr(c.binding.ptr)- }- if c.fingerprint.ptr != none {- bytes.free_ptr(c.fingerprint.ptr)- }- if c.repo_name.ptr != none {- bytes.free_ptr(c.repo_name.ptr)- }- if c.last_error.ptr != none {- bytes.free_ptr(c.last_error.ptr)- }- @free(c as ref void)-}--fn clear_error(c: mut ref Client) void = trust {- if c.last_error.ptr != none {- bytes.free_ptr(c.last_error.ptr)- c.last_error = bytes.empty()- }-}--fn set_error(c: mut ref Client, text: bytes.Bytes) void = trust {- clear_error(c)- c.last_error = bytes.Bytes.dup(text)-}--/// Return the most recent client-side protocol error. The result is owned.-pub fn error_text(c: ref Client) bytes.Bytes = trust {- if c.last_error.ptr == none {- return bytes.empty()- }- return bytes.Bytes.dup(c.last_error)-}--fn error_code_name(code: u8) bytes.Bytes = {- if code == wire.ERR_UNSUPPORTED_VERSION {- return bytes.bytes(c"unsupported protocol version", 28)- }- if code == wire.ERR_BAD_FRAME {- return bytes.bytes(c"bad frame", 9)- }- if code == wire.ERR_NOT_FOUND {- return bytes.bytes(c"object not found", 16)- }- if code == wire.ERR_HASH_MISMATCH {- return bytes.bytes(c"hash mismatch", 13)- }- if code == wire.ERR_NON_CANONICAL {- return bytes.bytes(c"non-canonical object", 20)- }- if code == wire.ERR_MISSING_CLOSURE {- return bytes.bytes(c"missing object closure", 22)- }- if code == wire.ERR_REF_CONFLICT {- return bytes.bytes(c"ref conflict", 12)- }- if code == wire.ERR_REJECTED {- return bytes.bytes(c"request rejected", 16)- }- if code == wire.ERR_INTERNAL {- return bytes.bytes(c"server internal error", 21)- }- if code == wire.ERR_UNAUTHENTICATED {- return bytes.bytes(c"authentication required", 23)- }- if code == wire.ERR_FORBIDDEN {- return bytes.bytes(c"permission denied", 17)- }- if code == wire.ERR_AUTH_FAILED {- return bytes.bytes(c"authentication failed", 21)- }- if code == wire.ERR_QUOTA {- return bytes.bytes(c"storage quota exceeded", 23)- }- if code == wire.ERR_TOO_LARGE {- return bytes.bytes(c"push too large", 14)- }- return bytes.bytes(c"unknown server error", 20)-}--fn set_error_frame(c: mut ref Client, f: wire.Frame) void = trust {- val code: u8 = wire.read_error(f.payload)- val name: bytes.Bytes = error_code_name(code)- val message: bytes.Bytes = wire.error_message(f.payload)- val b: mut buf.Buf = buf.new(name.len + message.len + 32)- buf.Buf.put_bytes(b, bytes.bytes(c"server error: ", 14))- buf.Buf.put_bytes(b, name)- if message.len > 0 {- buf.Buf.put_bytes(b, bytes.bytes(c": ", 2))- buf.Buf.put_bytes(b, message)- }- set_error(c, buf.Buf.view(b))- buf.Buf.free(b)- if message.ptr != none {- bytes.free_owned(message)- }-}--fn set_error_kind(c: mut ref Client, context: bytes.Bytes, kind: u8) void = trust {- val b: mut buf.Buf = buf.new(context.len + 32)- buf.Buf.put_bytes(b, context)- buf.Buf.put_bytes(b, bytes.bytes(c" (message kind ", 15))- buf.Buf.put_u8(b, kind)- buf.Buf.put_u8(b, 41)- set_error(c, buf.Buf.view(b))- buf.Buf.free(b)-}--fn id_text(id: objid.Id) bytes.Bytes = trust {- val hex: ref u8 = objid.Id.hex(id)- val out: bytes.Bytes = bytes.Bytes.dup(bytes.from_cstr(hex))- @free(hex as ref void)- return out-}--fn set_error_object(c: mut ref Client, context: bytes.Bytes, id: objid.Id) void = trust {- val hex: bytes.Bytes = id_text(id)- val b: mut buf.Buf = buf.new(context.len + hex.len + 8)- buf.Buf.put_bytes(b, context)- buf.Buf.put_u8(b, 32)- buf.Buf.put_bytes(b, hex)- set_error(c, buf.Buf.view(b))- buf.Buf.free(b)- bytes.free_owned(hex)-}--fn request(c: mut ref Client, kind: u8, payload: bytes.Bytes) option[wire.Frame] = trust {- val rid: u32 = (time.unix_now_millis() & 0x7fffffff) as u32- if !wire.write_frame(c.s, kind, rid, payload) {- set_error(c, bytes.bytes(c"connection closed while sending request", 39))- return none- }- val f_opt = wire.read_frame(c.s)- match f_opt {- some f => {- if f.kind == wire.ERROR {- set_error_frame(c, f)- wire.free_frame(f)- return none- }- return some f- }- none => {- set_error(c, bytes.bytes(c"connection closed while waiting for server response", 51))- return none- }- }-}--pub fn list_refs(c: mut ref Client) option[list[msg.RefInfo]] = trust {- val f_opt = request(c, wire.LIST_REFS, bytes.empty())- if f_opt is some f {- if f.kind != wire.REFS {- set_error_kind(c, bytes.bytes(c"unexpected response to ref listing", 34), f.kind)- wire.free_frame(f)- return none- }- val dec = msg.decode_refs(f.payload)- wire.free_frame(f)- if dec is ok v {- return some v- }- }- return none-}--pub fn negotiate(- c: mut ref Client,- wants: list[bytes.Bytes],- haves: list[bytes.Bytes]-) bool = trust {- val body: bytes.Bytes = msg.encode_negotiate(wants, haves)- val f_opt = request(c, wire.NEGOTIATE, body)- if f_opt is some f {- if f.kind == wire.NEGOTIATE_OK {- wire.free_frame(f)- return true- }- set_error_kind(c, bytes.bytes(c"unexpected response to negotiation", 34), f.kind)- wire.free_frame(f)- return false- }- return false-}--fn parse_record(data: bytes.Bytes) option[IncomingRecord] = trust {- if data.len < 35 {- return none- }- val r: mut reader.Reader = reader.new(data.ptr, data.len)- val idp: ref u8 = reader.Reader.read_id(r)?- val kind: u8 = reader.Reader.read_u8(r)?- val comp: u8 = reader.Reader.read_u8(r)?- val raw_len: u64 = reader.Reader.read_varint(r)?- val stored_len: u64 = reader.Reader.read_varint(r)?- if raw_len == 0 || raw_len > 67108864 {- return none- }- val stored: bytes.Bytes = reader.Reader.read_raw(r, stored_len as usize)?- if !reader.Reader.at_end(r) {- return none- }- val idcopy: ref u8 = @alloc(32) as ref u8- @memcpy(idcopy as ref void, idp as ref void, 32)- if comp == 0 {- if stored.len != raw_len as usize {- @free(idcopy as ref void)- return none- }- return some IncomingRecord{- id: bytes.bytes(idcopy, 32),- kind: kind,- body: bytes.Bytes.dup(stored)- }- }- val dec = zstd.decompress(stored, raw_len as usize)- if dec is some d {- return some IncomingRecord{- id: bytes.bytes(idcopy, 32),- kind: kind,- body: d- }- }- @free(idcopy as ref void)- return none-}--fn receive_stream(c: mut ref Client, w: mut ref writer.Writer) bool = trust {- val hash: ref void = @alloc(b3.hasher_state_size()) as ref void- b3.hasher_init(hash)- val good: mut bool = true- for {- val f_opt = wire.read_frame(c.s)- val f: mut wire.Frame = wire.Frame{- kind: 0,- request_id: 0,- payload: bytes.empty(),- base: bytes.empty()- }- match f_opt {- some x => {- f = x- }- none => {- set_error(c, bytes.bytes(c"connection closed while receiving data", 38))- good = false- break- }- }- if f.kind == wire.END {- val digest: ref u8 = @alloc(32) as ref u8- b3.hasher_final(hash, digest)- if f.payload.len != 32 || !bytes.Bytes.eql(bytes.bytes(digest, 32), f.payload) {- set_error(c, bytes.bytes(c"server sent a corrupt transfer checksum", 39))- good = false- }- bytes.free_ptr(digest)- wire.free_frame(f)- break- }- if f.kind == wire.ERROR {- set_error_frame(c, f)- wire.free_frame(f)- good = false- break- }- if f.kind != wire.RECORDS {- set_error_kind(c, bytes.bytes(c"unexpected message while receiving data", 39), f.kind)- wire.free_frame(f)- good = false- break- }- b3.hasher_update(hash, f.payload.ptr, f.payload.len)- val pr = parse_record(f.payload)- if pr is none {- }- if pr is some rec {- val computed: objid.Id = objid.object_id(rec.kind, rec.body)- if !objid.Id.eql(computed, objid.id(rec.id.ptr)) {- good = false- } else {- writer.add_known(w, rec.kind, objid.id(rec.id.ptr), rec.body)- }- bytes.free_ptr(computed.ptr)- bytes.free_ptr(rec.id.ptr)- } else {- good = false- }- wire.free_frame(f)- if !good {- break- }- }- @free(hash as ref void)- return good-}--fn open_writer(repo: layout.Repo) option[ref writer.Writer] = trust {- return writer.open(repo)-}--pub fn fetch_skeleton(c: mut ref Client, repo: layout.Repo, wants: list[bytes.Bytes]) bool = trust {- val body: bytes.Bytes = msg.encode_ids(wants)- val rid: u32 = (time.unix_now_millis() & 0x7fffffff) as u32- if !wire.write_frame(c.s, wire.FETCH_SKELETON, rid, body) {- set_error(c, bytes.bytes(c"connection closed while requesting objects", 42))- return false- }- val w_opt = open_writer(repo)- val w: mut ref writer.Writer = none- match w_opt {- some x => {- w = x- }- none => {- set_error(c, bytes.bytes(c"cannot open a local pack for incoming objects", 45))- return false- }- }- val passed: bool = receive_stream(c, w)- if !passed {- writer.abort(w)- return false- }- return writer.finish(w) == 0-}--pub fn get_chunks(c: mut ref Client, repo: layout.Repo, ids: list[bytes.Bytes]) bool = trust {- if @len(ids) == 0 {- return true- }- val body: bytes.Bytes = msg.encode_ids(ids)- val rid: u32 = (time.unix_now_millis() & 0x7fffffff) as u32- if !wire.write_frame(c.s, wire.GET_CHUNKS, rid, body) {- set_error(c, bytes.bytes(c"connection closed while requesting chunks", 41))- return false- }- val w_opt = open_writer(repo)- val w: mut ref writer.Writer = none- match w_opt {- some x => {- w = x- }- none => {- set_error(c, bytes.bytes(c"cannot open a local pack for incoming chunks", 44))- return false- }- }- val passed: bool = receive_stream(c, w)- if !passed {- writer.abort(w)- return false- }- return writer.finish(w) == 0-}--pub fn have_query(c: mut ref Client, ids: list[bytes.Bytes]) option[list[u64]] = trust {- val body: bytes.Bytes = msg.encode_ids(ids)- val f_opt = request(c, wire.HAVE_QUERY, body)- if f_opt is some f {- if f.kind == wire.HAVE_BITMAP {- val dec = msg.decode_bitmap(f.payload)- wire.free_frame(f)- if dec is ok v {- return some v- }- } else {- wire.free_frame(f)- }- }- return none-}--fn type_of(handles: list[ref store.Handle], id: objid.Id) u8 = trust {- val loc: mut store.Loc = store.Loc{pack_index: 0, record_index: 0, kind: 0}- if store.find_handles(handles, id, loc) {- return loc.kind- }- return 0-}--fn make_record(id: objid.Id, kind: u8, body: bytes.Bytes) bytes.Bytes = trust {- val b: mut buf.Buf = buf.new(body.len + 64)- buf.Buf.put_raw(b, id.ptr, 32)- buf.Buf.put_u8(b, kind)- buf.Buf.put_u8(b, 0)- buf.Buf.put_varint(b, body.len as u64)- buf.Buf.put_varint(b, body.len as u64)- buf.Buf.put_bytes(b, body)- val out: bytes.Bytes = bytes.Bytes.dup(buf.Buf.view(b))- buf.Buf.free(b)- return out-}--pub fn push_objects(c: mut ref Client, repo: layout.Repo, ids: list[objid.Id]) bool = trust {- val rid: u32 = (time.unix_now_millis() & 0x7fffffff) as u32- if !wire.write_frame(c.s, wire.PUT_RECORDS, rid, bytes.empty()) {- set_error(c, bytes.bytes(c"connection closed while starting push", 37))- return false- }- val st: store.Store = store.open_all(repo)- val hash: ref void = @alloc(b3.hasher_state_size()) as ref void- b3.hasher_init(hash)- val good: mut bool = true- for id in ids {- val kind: u8 = type_of(st.handles, id)- if kind == 0 {- set_error_object(c, bytes.bytes(c"local object is missing from the store:", 39), id)- good = false- break- }- val body_opt = state.read_body(st.handles, id, kind)- val body: mut bytes.Bytes = bytes.empty()- if body_opt is some b {- body = b- } else {- set_error_object(c, bytes.bytes(c"cannot read local object from the store:", 40), id)- good = false- break- }- val rec: bytes.Bytes = make_record(id, kind, body)- b3.hasher_update(hash, rec.ptr, rec.len)- if !wire.write_frame(c.s, wire.RECORDS, rid, rec) {- set_error_object(c, bytes.bytes(c"connection closed while sending object:", 39), id)- files_free(body)- good = false- break- }- files_free(body)- }- val digest: ref u8 = @alloc(32) as ref u8- b3.hasher_final(hash, digest)- if good {- if !wire.write_frame(c.s, wire.END, rid, bytes.bytes(digest, 32)) {- set_error(c, bytes.bytes(c"connection closed while finishing push", 38))- good = false- }- } else {- bytes.free_ptr(digest)- }- @free(hash as ref void)- store.close(st)- if !good {- return false- }- val ack = wire.read_frame(c.s)- if ack is none {- set_error(c, bytes.bytes(c"server closed the connection before acknowledging the push", 58))- return false- }- val f: mut wire.Frame = wire.Frame{- kind: 0,- request_id: 0,- payload: bytes.empty(),- base: bytes.empty()- }- match ack {- some x => {- f = x- }- none => {- return false- }- }- if f.kind == wire.END {- wire.free_frame(f)- return true- }- if f.kind == wire.ERROR {- set_error_frame(c, f)- wire.free_frame(f)- return false- }- set_error_kind(c, bytes.bytes(c"unexpected response to object push", 34), f.kind)- wire.free_frame(f)- return false-}--fn files_free(b: bytes.Bytes) void = trust {- if b.ptr != none {- bytes.free_owned(b)- }-}--pub fn update_refs(c: mut ref Client, updates: list[msg.UpdateRef]) bool = trust {- val body: bytes.Bytes = msg.encode_update_refs(updates)- val f_opt = request(c, wire.UPDATE_REFS, body)- if f_opt is some f {- if f.kind == wire.UPDATE_REFS_OK {- wire.free_frame(f)- return true- }- set_error_kind(c, bytes.bytes(c"unexpected response to ref update", 33), f.kind)- wire.free_frame(f)- return false- }- return false-}--pub fn whoami(- url: bytes.Bytes,- key_name: bytes.Bytes,- repo_name: bytes.Bytes-) option[WhoAmI] = trust {- return whoami_pinned(url, key_name, repo_name, bytes.empty())-}--pub fn whoami_pinned(- url: bytes.Bytes,- key_name: bytes.Bytes,- repo_name: bytes.Bytes,- tls_pin: bytes.Bytes-) option[WhoAmI] = trust {- val c_opt = connect_pinned(url, key_name, repo_name, tls_pin)- val c: mut ref Client = none- match c_opt {- some v => {- c = v- }- none => {- return none- }- }- val f_opt = request(c, wire.WHOAMI, bytes.empty())- if f_opt is some f {- if f.kind == wire.WHOAMI_OK {- val r: mut reader.Reader = reader.new(f.payload.ptr, f.payload.len)- val role: u8 = reader.Reader.read_u8(r)?- val fp: bytes.Bytes = reader.Reader.read_bytes(r, 64)?- val out: WhoAmI = WhoAmI{- role: role,- fingerprint: bytes.Bytes.dup(fp)- }- wire.free_frame(f)- free_client(c)- return some out- }- wire.free_frame(f)- }- free_client(c)- return none-}--/// The repository name to send in HELLO for a URL.-pub fn url_repo_name(url: bytes.Bytes) bytes.Bytes = trust {- val u_opt = parse_url(url)- val u: mut Url = Url{tls: false, host: bytes.empty(), port: 0, path: bytes.empty(), ssh: false}- match u_opt {- some uv => {- u = uv- }- none => {- return bytes.empty()- }- }- val out: mut bytes.Bytes = bytes.empty()- if u.tls {- out = bytes.Bytes.dup(u.path)- }- if u.host.ptr != none {- bytes.free_ptr(u.host.ptr)- }- if u.path.ptr != none {- bytes.free_ptr(u.path.ptr)- }- return out-}--test "client formats server error frames" {- trust {- val c: mut ref Client = @alloc(@sizeof(Client)) as ref Client- c.last_error = bytes.empty()- val b: mut buf.Buf = buf.new(64)- buf.Buf.put_u8(b, wire.ERR_FORBIDDEN)- buf.Buf.put_length_prefixed(b, bytes.bytes(c"write role required", 19))- val payload: bytes.Bytes = bytes.Bytes.dup(buf.Buf.view(b))- val f: wire.Frame = wire.Frame{- kind: wire.ERROR,- request_id: 1,- payload: payload,- base: bytes.empty()- }- set_error_frame(c, f)- val expected: bytes.Bytes = bytes.bytes(- c"server error: permission denied: write role required",- 52- )- assert bytes.Bytes.eql(c.last_error, expected)- clear_error(c)- bytes.free_owned(payload)- buf.Buf.free(b)- @free(c as ref void)- }-}--- a/veins/src/protocol/messages.sx+++ /dev/null@@ -1,443 +0,0 @@-/// Encoding for the native protocol's structured messages.--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 derr = use("../core/error.sx")--pub val PROTOCOL_VERSION: u16 = 1--pub type Hello = {- min_version: mut u16- max_version: mut u16- capabilities: mut list[bytes.Bytes]- repo: mut bytes.Bytes- client_nonce: mut bytes.Bytes-}--pub type HelloOk = {- version: mut u16- capabilities: mut list[bytes.Bytes]- server_nonce: mut bytes.Bytes- auth_required: mut u8-}--pub type Auth = {- public_key: mut bytes.Bytes- signature: mut bytes.Bytes-}--pub type AuthOk = {- role: mut u8- fingerprint: mut bytes.Bytes-}--pub type RefInfo = {- name: mut bytes.Bytes- target: mut bytes.Bytes- change_id: mut bytes.Bytes- kind: mut u8-}--pub type UpdateRef = {- name: mut bytes.Bytes- expected: mut bytes.Bytes- target: mut bytes.Bytes-}--pub type Negotiate = {- wants: mut list[bytes.Bytes]- haves: mut list[bytes.Bytes]-}--fn put_u16_be(b: mut buf.Buf, v: u16) void = {- buf.Buf.put_u8(b, ((v >> 8) & 255) as u8)- buf.Buf.put_u8(b, (v & 255) as u8)-}--fn read_u16_be(r: mut reader.Reader) result[u16, derr.DecodeError] = {- val a: u8 = reader.Reader.read_u8(r)?- val c: u8 = reader.Reader.read_u8(r)?- return ok (((a as u16) << 8) | (c as u16))-}--fn put_list(b: mut buf.Buf, xs: list[bytes.Bytes]) void = {- buf.Buf.put_varint(b, @len(xs) as u64)- for x in xs {- buf.Buf.put_length_prefixed(b, x)- }-}--fn read_list(r: mut reader.Reader, max: usize) result[list[bytes.Bytes], derr.DecodeError] = {- val n: usize = reader.Reader.read_list_len(r, max)?- val out: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()- val i: mut usize = 0- for i < n {- val v: bytes.Bytes = reader.Reader.read_bytes(r, 4096)?- @append(out, bytes.Bytes.dup(v))- i++- }- return ok out-}--fn optional_id(b: mut buf.Buf, id: bytes.Bytes) void = {- if id.ptr == none || id.len != 32 {- buf.Buf.put_u8(b, 0)- } else {- buf.Buf.put_u8(b, 1)- buf.Buf.put_raw(b, id.ptr, 32)- }-}--fn read_optional_id(r: mut reader.Reader) result[bytes.Bytes, derr.DecodeError] = {- val tag: u8 = reader.Reader.read_u8(r)?- if tag == 0 {- return ok bytes.empty()- }- if tag != 1 {- return err derr.fail(derr.ErrorKind.InvalidValue, reader.Reader.offset(r) - 1)- }- val p: ref u8 = reader.Reader.read_id(r)?- return ok bytes.Bytes.slice(bytes.bytes(p, 32), 0, 32)-}--pub fn encode_hello(h: Hello) bytes.Bytes = {- val b: mut buf.Buf = buf.new(128)- put_u16_be(b, h.min_version)- put_u16_be(b, h.max_version)- put_list(b, h.capabilities)- buf.Buf.put_length_prefixed(b, h.repo)- buf.Buf.put_length_prefixed(b, h.client_nonce)- val out: bytes.Bytes = bytes.Bytes.dup(buf.Buf.view(b))- buf.Buf.free(b)- return out-}--pub fn decode_hello(data: bytes.Bytes) result[Hello, derr.DecodeError] = {- val r: mut reader.Reader = reader.new(data.ptr, data.len)- val mn: u16 = read_u16_be(r)?- val mx: u16 = read_u16_be(r)?- val caps: list[bytes.Bytes] = read_list(r, 64)?- val repo_raw: bytes.Bytes = reader.Reader.read_bytes(r, 4096)?- val nonce_raw: bytes.Bytes = reader.Reader.read_bytes(r, 64)?- reader.Reader.finish(r)?- return ok Hello{- min_version: mn,- max_version: mx,- capabilities: caps,- repo: bytes.Bytes.dup(repo_raw),- client_nonce: bytes.Bytes.dup(nonce_raw)- }-}--pub fn encode_hello_ok(h: HelloOk) bytes.Bytes = {- val b: mut buf.Buf = buf.new(128)- put_u16_be(b, h.version)- put_list(b, h.capabilities)- buf.Buf.put_length_prefixed(b, h.server_nonce)- buf.Buf.put_u8(b, h.auth_required)- val out: bytes.Bytes = bytes.Bytes.dup(buf.Buf.view(b))- buf.Buf.free(b)- return out-}--pub fn decode_hello_ok(data: bytes.Bytes) result[HelloOk, derr.DecodeError] = {- val r: mut reader.Reader = reader.new(data.ptr, data.len)- val v: u16 = read_u16_be(r)?- val caps: list[bytes.Bytes] = read_list(r, 64)?- val nonce: bytes.Bytes = reader.Reader.read_bytes(r, 64)?- val auth: u8 = reader.Reader.read_u8(r)?- reader.Reader.finish(r)?- return ok HelloOk{- version: v,- capabilities: caps,- server_nonce: bytes.Bytes.dup(nonce),- auth_required: auth- }-}--pub fn encode_auth(a: Auth) bytes.Bytes = {- val b: mut buf.Buf = buf.new(128)- buf.Buf.put_length_prefixed(b, a.public_key)- buf.Buf.put_length_prefixed(b, a.signature)- val out: bytes.Bytes = bytes.Bytes.dup(buf.Buf.view(b))- buf.Buf.free(b)- return out-}--pub fn decode_auth(data: bytes.Bytes) result[Auth, derr.DecodeError] = {- val r: mut reader.Reader = reader.new(data.ptr, data.len)- val pub_raw: bytes.Bytes = reader.Reader.read_bytes(r, 64)?- val sig: bytes.Bytes = reader.Reader.read_bytes(r, 128)?- reader.Reader.finish(r)?- return ok Auth{- public_key: bytes.Bytes.dup(pub_raw),- signature: bytes.Bytes.dup(sig)- }-}--pub fn encode_auth_ok(a: AuthOk) bytes.Bytes = {- val b: mut buf.Buf = buf.new(64)- buf.Buf.put_u8(b, a.role)- buf.Buf.put_length_prefixed(b, a.fingerprint)- val out: bytes.Bytes = bytes.Bytes.dup(buf.Buf.view(b))- buf.Buf.free(b)- return out-}--pub fn decode_auth_ok(data: bytes.Bytes) result[AuthOk, derr.DecodeError] = {- val r: mut reader.Reader = reader.new(data.ptr, data.len)- val role: u8 = reader.Reader.read_u8(r)?- val fp: bytes.Bytes = reader.Reader.read_bytes(r, 64)?- reader.Reader.finish(r)?- return ok AuthOk{role: role, fingerprint: bytes.Bytes.dup(fp)}-}--pub fn encode_refs(refs: list[RefInfo]) bytes.Bytes = {- val b: mut buf.Buf = buf.new(256)- buf.Buf.put_varint(b, @len(refs) as u64)- for r in refs {- buf.Buf.put_length_prefixed(b, r.name)- buf.Buf.put_raw(b, r.target.ptr, 32)- buf.Buf.put_length_prefixed(b, r.change_id)- buf.Buf.put_u8(b, r.kind)- }- val out: bytes.Bytes = bytes.Bytes.dup(buf.Buf.view(b))- buf.Buf.free(b)- return out-}--pub fn decode_refs(data: bytes.Bytes) result[list[RefInfo], derr.DecodeError] = {- val r: mut reader.Reader = reader.new(data.ptr, data.len)- val n: usize = reader.Reader.read_list_len(r, 1000000)?- val out: mut list[RefInfo] = lists.new[RefInfo]()- val i: mut usize = 0- for i < n {- val name: bytes.Bytes = reader.Reader.read_bytes(r, 4096)?- val p: ref u8 = reader.Reader.read_id(r)?- val cid: bytes.Bytes = reader.Reader.read_bytes(r, 64)?- val rkind: u8 = reader.Reader.read_u8(r)?- val target: ref u8 = @alloc(32) as ref u8- trust {- @memcpy(target as ref void, p as ref void, 32)- }- @append(- out,- RefInfo{- name: bytes.Bytes.dup(name),- target: bytes.bytes(target, 32),- change_id: bytes.Bytes.dup(cid),- kind: rkind- }- )- i++- }- reader.Reader.finish(r)?- return ok out-}--pub fn encode_ids(ids: list[bytes.Bytes]) bytes.Bytes = {- val b: mut buf.Buf = buf.new(ids.len * 32 + 8)- buf.Buf.put_varint(b, @len(ids) as u64)- for id in ids {- buf.Buf.put_raw(b, id.ptr, 32)- }- val out: bytes.Bytes = bytes.Bytes.dup(buf.Buf.view(b))- buf.Buf.free(b)- return out-}--pub fn decode_ids(data: bytes.Bytes, max: usize) result[list[bytes.Bytes], derr.DecodeError] = {- val r: mut reader.Reader = reader.new(data.ptr, data.len)- val n: usize = reader.Reader.read_list_len(r, max)?- val out: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()- val i: mut usize = 0- for i < n {- val p: ref u8 = reader.Reader.read_id(r)?- val copy: ref u8 = @alloc(32) as ref u8- trust {- @memcpy(copy as ref void, p as ref void, 32)- }- @append(out, bytes.bytes(copy, 32))- i++- }- reader.Reader.finish(r)?- return ok out-}--pub fn encode_negotiate(wants: list[bytes.Bytes], haves: list[bytes.Bytes]) bytes.Bytes = {- val b: mut buf.Buf = buf.new(256)- buf.Buf.put_varint(b, @len(wants) as u64)- for id in wants {- buf.Buf.put_raw(b, id.ptr, 32)- }- buf.Buf.put_varint(b, @len(haves) as u64)- for id in haves {- buf.Buf.put_raw(b, id.ptr, 32)- }- val out: bytes.Bytes = bytes.Bytes.dup(buf.Buf.view(b))- buf.Buf.free(b)- return out-}--pub fn decode_negotiate(- data: bytes.Bytes-) result[Negotiate, derr.DecodeError] = {- val r: mut reader.Reader = reader.new(data.ptr, data.len)- val nw: usize = reader.Reader.read_list_len(r, 1000000)?- val wants: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()- val i: mut usize = 0- for i < nw {- val p: ref u8 = reader.Reader.read_id(r)?- val copy: ref u8 = @alloc(32) as ref u8- trust {- @memcpy(copy as ref void, p as ref void, 32)- }- @append(wants, bytes.bytes(copy, 32))- i++- }- val nh: usize = reader.Reader.read_list_len(r, 1000000)?- val haves: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()- val j: mut usize = 0- for j < nh {- val p2: ref u8 = reader.Reader.read_id(r)?- val copy2: ref u8 = @alloc(32) as ref u8- trust {- @memcpy(copy2 as ref void, p2 as ref void, 32)- }- @append(haves, bytes.bytes(copy2, 32))- j++- }- reader.Reader.finish(r)?- return ok Negotiate{wants: wants, haves: haves}-}--pub fn encode_negotiate_ok(known: list[u64], enough: u8) bytes.Bytes = {- val b: mut buf.Buf = buf.new(64)- buf.Buf.put_u8(b, enough)- buf.Buf.put_varint(b, @len(known) as u64)- for k in known {- buf.Buf.put_u8(b, k)- }- val out: bytes.Bytes = bytes.Bytes.dup(buf.Buf.view(b))- buf.Buf.free(b)- return out-}--pub fn encode_bitmap(bits: list[u64]) bytes.Bytes = {- val b: mut buf.Buf = buf.new(bits.len + 8)- buf.Buf.put_varint(b, @len(bits) as u64)- for x in bits {- buf.Buf.put_u8(b, x as u8)- }- val out: bytes.Bytes = bytes.Bytes.dup(buf.Buf.view(b))- buf.Buf.free(b)- return out-}--pub fn decode_bitmap(data: bytes.Bytes) result[list[u64], derr.DecodeError] = {- val r: mut reader.Reader = reader.new(data.ptr, data.len)- val n: usize = reader.Reader.read_list_len(r, 1000000)?- val out: mut list[u64] = lists.new[u8]()- val i: mut usize = 0- for i < n {- val bv: u8 = reader.Reader.read_u8(r)?- @append(out, bv as u64)- i++- }- reader.Reader.finish(r)?- return ok out-}--pub fn encode_update_refs(updates: list[UpdateRef]) bytes.Bytes = {- val b: mut buf.Buf = buf.new(256)- buf.Buf.put_varint(b, @len(updates) as u64)- for u in updates {- buf.Buf.put_length_prefixed(b, u.name)- optional_id(b, u.expected)- optional_id(b, u.target)- }- val out: bytes.Bytes = bytes.Bytes.dup(buf.Buf.view(b))- buf.Buf.free(b)- return out-}--pub fn decode_update_refs(data: bytes.Bytes) result[list[UpdateRef], derr.DecodeError] = {- val r: mut reader.Reader = reader.new(data.ptr, data.len)- val n: usize = reader.Reader.read_list_len(r, 1000000)?- val out: mut list[UpdateRef] = lists.new[UpdateRef]()- val i: mut usize = 0- for i < n {- val name: bytes.Bytes = reader.Reader.read_bytes(r, 4096)?- val expected: bytes.Bytes = read_optional_id(r)?- val target: bytes.Bytes = read_optional_id(r)?- @append(- out,- UpdateRef{- name: bytes.Bytes.dup(name),- expected: bytes.Bytes.dup(expected),- target: bytes.Bytes.dup(target)- }- )- i++- }- reader.Reader.finish(r)?- return ok out-}--pub fn free_hello(h: Hello) void = trust {- free_list(h.capabilities)- if h.repo.ptr != none {- bytes.free_ptr(h.repo.ptr)- }- if h.client_nonce.ptr != none {- bytes.free_ptr(h.client_nonce.ptr)- }-}--pub fn free_hello_ok(h: HelloOk) void = trust {- free_list(h.capabilities)- if h.server_nonce.ptr != none {- bytes.free_ptr(h.server_nonce.ptr)- }-}--pub fn free_refs(rs: list[RefInfo]) void = trust {- for r in rs {- if r.name.ptr != none {- bytes.free_ptr(r.name.ptr)- }- if r.target.ptr != none {- bytes.free_ptr(r.target.ptr)- }- if r.change_id.ptr != none {- bytes.free_ptr(r.change_id.ptr)- }- }- @listfree(rs)-}--pub fn free_updates(us: list[UpdateRef]) void = trust {- for u in us {- if u.name.ptr != none {- bytes.free_ptr(u.name.ptr)- }- if u.expected.ptr != none {- bytes.free_ptr(u.expected.ptr)- }- if u.target.ptr != none {- bytes.free_ptr(u.target.ptr)- }- }- @listfree(us)-}--fn free_list(xs: list[bytes.Bytes]) void = trust {- for x in xs {- if x.ptr != none {- bytes.free_owned(x)- }- }- @listfree(xs)-}--- a/veins/src/protocol/promisor.sx+++ /dev/null@@ -1,153 +0,0 @@-/// Lazy chunk fetching for repositories cloned with promised blobs.--val bytes = use("../core/bytes.sx")-val lists = use("../core/lists.sx")-val objid = use("../object/id.sx")-val store = use("../store/store.sx")-val layout = use("../store/layout.sx")-val config = use("../core/repoconfig.sx")-val client = use("../protocol/client.sx")--fn key_for(remote: bytes.Bytes, field: bytes.Bytes) bytes.Bytes = trust {- val out: ref u8 = @alloc(7 + remote.len + 1 + field.len) as ref u8- @memcpy(out as ref void, c"remote." as ref void, 7)- @memcpy(@ptradd(out, 7) as ref void, remote.ptr as ref void, remote.len)- @store8(@ptradd(out, (7 + remote.len) as i64), 46)- @memcpy(@ptradd(out, (8 + remote.len) as i64) as ref void, field.ptr as ref void, field.len)- return bytes.bytes(out, 7 + remote.len + 1 + field.len)-}--val active: mut bool = false-val repo_ref: mut layout.Repo = @zeroed-val remote_ref: mut bytes.Bytes = @zeroed--pub fn configure(repo: layout.Repo, remote: bytes.Bytes) void = trust {- if active {- layout.free_repo(repo_ref)- bytes.free_owned(remote_ref)- }- repo_ref.root = bytes.Bytes.dup(repo.root)- remote_ref = bytes.Bytes.dup(remote)- active = true-}--pub fn is_active() bool = {- return active-}--fn find_sub(hay: bytes.Bytes, needle: bytes.Bytes) i64 = trust {- if needle.len > hay.len {- return -1- }- val i: mut usize = 0- for i <= hay.len - needle.len {- if bytes.Bytes.eql(bytes.Bytes.slice(hay, i, i + needle.len), needle) {- return i as i64- }- i++- }- return -1-}--/// Enable lazy fetching based on the repository's promisor configuration.-pub fn ensure(handles: list[ref store.Handle]) void = trust {- if active || @len(handles) == 0 {- return- }- val h = store.handle_list_at(handles, 0)- val path_b: bytes.Bytes = bytes.bytes(h.path.ptr, h.path.len)- val marker: bytes.Bytes = bytes.bytes(c"/.veins/store/packs/", 20)- val at: i64 = find_sub(path_b, marker)- if at <= 0 {- return- }- val root_b: bytes.Bytes = bytes.Bytes.slice(path_b, 0, at as usize)- val r: layout.Repo = layout.Repo{root: bytes.Bytes.dup(root_b)}- val pk: bytes.Bytes = bytes.bytes(c"promisor", 8)- val pv = config.get(r, pk)- if pv is some remote {- configure(r, remote)- bytes.free_owned(remote)- }- layout.free_repo(r)-}--fn load_chunk(id: objid.Id) option[bytes.Bytes] = trust {- val st: store.Store = store.open_all(repo_ref)- val loc: mut store.Loc = store.Loc{pack_index: 0, record_index: 0, kind: 0}- val found: bool = store.find_handles(st.handles, id, loc)- val out: mut option[bytes.Bytes] = none- if found {- val body = store.get_handles(st.handles, loc)- if body is ok b {- out = some bytes.Bytes.dup(b)- bytes.free_owned(b)- }- }- store.close(st)- return out-}--/// Fetch one missing chunk from the promisor remote.-pub fn fetch_chunk(id: objid.Id) option[bytes.Bytes] = trust {- if !active {- return none- }- val cached = load_chunk(id)- if cached is some c {- return some c- }- val uk: bytes.Bytes = key_for(remote_ref, bytes.bytes(c"url", 3))- val url_opt = config.get(repo_ref, uk)- bytes.free_owned(uk)- if url_opt is none {- return none- }- val url: mut bytes.Bytes = bytes.empty()- match url_opt {- some uv => {- url = uv- }- none => {- return none- }- }- val kk: bytes.Bytes = key_for(remote_ref, bytes.bytes(c"key", 3))- val key_opt = config.get(repo_ref, kk)- bytes.free_owned(kk)- val key: mut bytes.Bytes = bytes.empty()- if key_opt is some k {- key = k- }- val pk: bytes.Bytes = key_for(remote_ref, bytes.bytes(c"tls-pin", 7))- val pin_opt = config.get(repo_ref, pk)- bytes.free_owned(pk)- val pin: mut bytes.Bytes = bytes.empty()- if pin_opt is some p {- pin = p- }- val repo_name: bytes.Bytes = client.url_repo_name(url)- val c_opt = client.connect_pinned(url, key, repo_name, pin)- bytes.free_owned(url)- bytes.free_owned(key)- bytes.free_owned(pin)- bytes.free_owned(repo_name)- val c: mut ref client.Client = none- match c_opt {- some v => {- c = v- }- none => {- return none- }- }- val ids: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()- @append(ids, bytes.bytes(id.ptr, 32))- val fetched: bool = client.get_chunks(c, repo_ref, ids)- @listfree(ids)- client.free_client(c)- if !fetched {- return none- }- return load_chunk(id)-}--- a/veins/src/protocol/transfer.sx+++ /dev/null@@ -1,392 +0,0 @@-/// View construction and chunk selection shared by clone and fetch.--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 blob = use("../object/blob.sx")-val conflict = use("../object/conflict.sx")-val graph = use("../object/graph.sx")-val store = use("../store/store.sx")-val state = use("../store/state.sx")-val layout = use("../store/layout.sx")-val idmap = use("../store/idmap.sx")-val txnmod = use("../store/txn.sx")-val viewops = use("../store/viewops.sx")-val view = use("../object/view.sx")-val files = use("../io/files.sx")-val msg_refs = use("../protocol/messages.sx")-val checkout = use("../worktree/checkout.sx")-val repoconfig = use("../core/repoconfig.sx")--type ChunkWalk = {- handles: mut list[ref store.Handle]- blobs: mut idmap.IdSet- conflicts: mut idmap.IdSet- chunks: mut idmap.IdSet- out: mut list[bytes.Bytes]- objects: mut idmap.IdSet- obj_out: mut list[objid.Id]-}--fn id_bytes(id: objid.Id) bytes.Bytes = trust {- return bytes.bytes(id.ptr, 32)-}--fn add_object(cw: mut ref ChunkWalk, id: objid.Id) void = trust {- if idmap.put(cw.objects, id_bytes(id)) {- @append(cw.obj_out, viewops.copy_id(id))- }-}--fn walk_blob(cw: mut ref ChunkWalk, id: objid.Id) void = trust {- if !idmap.put(cw.blobs, id_bytes(id)) {- return- }- add_object(cw, id)- val body_opt = state.read_body(cw.handles, id, types.BLOB)- val body: mut bytes.Bytes = bytes.empty()- if body_opt is some b {- body = b- } else {- return- }- val dec = blob.decode(body)- if dec is ok bl {- if bl.form == blob.FORM_LEAF {- for e in bl.entries {- if idmap.put(cw.chunks, id_bytes(e.id)) {- val copy: ref u8 = @alloc(32) as ref u8- @memcpy(copy as ref void, e.id.ptr as ref void, 32)- @append(cw.out, bytes.bytes(copy, 32))- add_object(cw, e.id)- }- }- } elif bl.form == blob.FORM_INTERIOR {- for e in bl.entries {- walk_blob(cw, e.id)- }- }- blob.free_blob(bl)- }- files.free_buffer(body)-}--fn walk_conflict(cw: mut ref ChunkWalk, id: objid.Id) void = trust {- if !idmap.put(cw.conflicts, id_bytes(id)) {- return- }- add_object(cw, id)- val body_opt = state.read_body(cw.handles, id, types.CONFLICT)- val body: mut bytes.Bytes = bytes.empty()- if body_opt is some b {- body = b- } else {- return- }- val dec = conflict.decode(body)- if dec is ok c {- for v in c.adds {- if v.target.ptr != none {- walk_value(cw, v.kind, v.target)- }- }- for v in c.removes {- if v.target.ptr != none {- walk_value(cw, v.kind, v.target)- }- }- conflict.free_conflict(c)- }- files.free_buffer(body)-}--fn walk_value(cw: mut ref ChunkWalk, kind: u8, id: objid.Id) void = trust {- if kind == tree.KIND_SUBTREE {- walk_tree(cw, id)- } elif kind == tree.KIND_CONFLICT {- walk_conflict(cw, id)- } else {- walk_blob(cw, id)- }-}--fn walk_tree(cw: mut ref ChunkWalk, id: objid.Id) void = trust {- add_object(cw, id)- val body_opt = state.read_body(cw.handles, id, types.TREE)- val body: mut bytes.Bytes = bytes.empty()- if body_opt is some b {- body = b- } else {- return- }- val dec = tree.decode(body)- if dec is ok t {- for e in t.entries {- if e.kind == tree.KIND_SUBTREE {- walk_tree(cw, e.target)- } elif e.kind == tree.KIND_CONFLICT {- walk_conflict(cw, e.target)- } elif e.kind != tree.KIND_SUBMODULE {- walk_blob(cw, e.target)- }- }- tree.free_tree(t)- }- files.free_buffer(body)-}--/// Collect the leaf chunk IDs needed by the given commits.-pub fn chunks_for_commits(- handles: list[ref store.Handle],- commits: list[objid.Id]-) list[bytes.Bytes] = trust {- val cw: mut ChunkWalk = ChunkWalk{- handles: handles,- blobs: idmap.new(256),- conflicts: idmap.new(64),- chunks: idmap.new(256),- out: lists.new[bytes.Bytes](),- objects: idmap.new(256),- obj_out: lists.new[objid.Id]()- }- for c in commits {- val lc_opt = graph.load_commit(handles, c)- if lc_opt is some lc {- walk_tree(cw, lc.c.root_tree)- graph.free_loaded(lc)- }- }- idmap.free(cw.blobs)- idmap.free(cw.conflicts)- idmap.free(cw.chunks)- idmap.free(cw.objects)- free_ids_keep(cw.obj_out)- return cw.out-}--fn free_ids_keep(xs: list[objid.Id]) void = trust {- for x in xs {- if x.ptr != none {- bytes.free_owned(x)- }- }- @listfree(xs)-}--/// Collect every object reachable from the given commits, including chunks.-pub fn objects_for_commits(- handles: list[ref store.Handle],- commits: list[objid.Id]-) list[objid.Id] = trust {- val cw: mut ChunkWalk = ChunkWalk{- handles: handles,- blobs: idmap.new(256),- conflicts: idmap.new(64),- chunks: idmap.new(256),- out: lists.new[bytes.Bytes](),- objects: idmap.new(256),- obj_out: lists.new[objid.Id]()- }- for c in commits {- add_object(cw, c)- val lc_opt = graph.load_commit(handles, c)- if lc_opt is some lc {- walk_tree(cw, lc.c.root_tree)- graph.free_loaded(lc)- }- }- idmap.free(cw.blobs)- idmap.free(cw.conflicts)- idmap.free(cw.chunks)- idmap.free(cw.objects)- free_id_bytes(cw.out)- return cw.obj_out-}--pub fn free_id_bytes(xs: list[bytes.Bytes]) void = trust {- for x in xs {- if x.ptr != none {- bytes.free_owned(x)- }- }- @listfree(xs)-}--fn set_bookmark(v: mut ref view.View, name: bytes.Bytes, id: objid.Id) void = 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) {- @listfree(bm.targets.adds)- @listfree(bm.targets.removes)- bm.targets = view.empty_target_set()- @append(bm.targets.adds, viewops.copy_id(id))- return- }- }- i++- }- val bm: mut ref view.Bookmark = @alloc(@sizeof(view.Bookmark)) as ref view.Bookmark- bm.name = bytes.Bytes.dup(name)- bm.targets = view.empty_target_set()- @append(bm.targets.adds, viewops.copy_id(id))- @append(v.bookmarks, bm)-}--fn set_tag(v: mut ref view.View, name: bytes.Bytes, id: objid.Id) void = 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) {- t.target = viewops.copy_id(id)- return- }- }- i++- }- val t: mut ref view.TagRef = @alloc(@sizeof(view.TagRef)) as ref view.TagRef- t.name = bytes.Bytes.dup(name)- t.target = viewops.copy_id(id)- @append(v.tags, t)-}--fn set_remote(- v: mut ref view.View,- remote: bytes.Bytes,- name: bytes.Bytes,- id: objid.Id-) void = trust {- val i: mut usize = 0- for i < @len(v.remote_refs) {- val o = @get(v.remote_refs, i)- if o is some rr {- if bytes.Bytes.eql(rr.remote, remote) && bytes.Bytes.eql(rr.name, name) {- rr.target = viewops.copy_id(id)- return- }- }- i++- }- val rr: mut ref view.RemoteRef = @alloc(@sizeof(view.RemoteRef)) as ref view.RemoteRef- rr.remote = bytes.Bytes.dup(remote)- rr.name = bytes.Bytes.dup(name)- rr.target = viewops.copy_id(id)- @append(v.remote_refs, rr)-}--fn has_bookmark(v: ref view.View, name: bytes.Bytes) bool = trust {- for bm in v.bookmarks {- if bytes.Bytes.eql(bm.name, name) {- return true- }- }- return false-}--fn set_workspace(v: mut ref view.View, id: objid.Id) void = trust {- viewops.set_workspace(v, id)-}--pub fn default_target(refs: list[msg_refs.RefInfo]) option[objid.Id] = trust {- for r in refs {- if r.kind == 0 && (bytes.Bytes.eql(- r.name,- bytes.bytes(c"main", 4)- ) || bytes.Bytes.eql(r.name, bytes.bytes(c"master", 6))) {- return some objid.id(r.target.ptr)- }- }- for r in refs {- if r.kind == 0 {- return some objid.id(r.target.ptr)- }- }- return none-}--pub fn default_ref_name(refs: list[msg_refs.RefInfo]) option[bytes.Bytes] = trust {- for r in refs {- if r.kind == 0 && (bytes.Bytes.eql(- r.name,- bytes.bytes(c"main", 4)- ) || bytes.Bytes.eql(r.name, bytes.bytes(c"master", 6))) {- return some r.name- }- }- for r in refs {- if r.kind == 0 {- return some r.name- }- }- return none-}--/// Apply remote refs to the local view in one operation.-pub fn apply_refs(- repo: layout.Repo,- refs: list[msg_refs.RefInfo],- remote: bytes.Bytes,- clone: bool-) i32 = trust {- val tx_opt = txnmod.begin(repo)- val tx: mut ref txnmod.Txn = none- match tx_opt {- some t => {- tx = t- }- none => {- return 1- }- }- for r in refs {- if r.target.ptr == none {- continue- }- val id: objid.Id = objid.id(r.target.ptr)- if r.kind == 1 {- set_tag(tx.view, r.name, id)- } elif clone {- set_bookmark(tx.view, r.name, id)- } else {- set_remote(tx.view, remote, r.name, id)- if !has_bookmark(tx.view, r.name) {- set_bookmark(tx.view, r.name, id)- }- }- }- viewops.rebuild_heads(tx.view)- if clone {- val dt = default_target(refs)- if dt is some id2 {- val child_opt = checkout.create_working_copy_commit(tx, repo, id2)- match child_opt {- some child => {- set_workspace(tx.view, child)- viewops.rebuild_heads(tx.view)- if child.ptr != none {- val cp: mut ref void = child.ptr as ref void- @free(cp)- }- }- none => {- txnmod.abort(tx)- return 1- }- }- }- }- val status: i32 = txnmod.finish(tx, bytes.bytes(c"clone", 5))- if status == 0 && clone {- val name_opt = default_ref_name(refs)- if name_opt is some name {- val _ = repoconfig.set_current_bookmark(repo, name)- } else {- val _ = repoconfig.clear_current_bookmark(repo)- }- }- return status-}--- a/veins/src/protocol/wire.sx+++ /dev/null@@ -1,280 +0,0 @@-/// Native protocol framing and message encoding helpers.--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 stream = use("../net/stream.sx")-val derr = use("../core/error.sx")--pub val MAX_FRAME: usize = 16777216--pub val HELLO: u8 = 1-pub val HELLO_OK: u8 = 2-pub val AUTH: u8 = 3-pub val AUTH_OK: u8 = 4-pub val WHOAMI: u8 = 5-pub val WHOAMI_OK: u8 = 6-pub val LIST_REFS: u8 = 7-pub val REFS: u8 = 8-pub val NEGOTIATE: u8 = 9-pub val NEGOTIATE_OK: u8 = 10-pub val FETCH_SKELETON: u8 = 11-pub val GET_CHUNKS: u8 = 12-pub val HAVE_QUERY: u8 = 13-pub val HAVE_BITMAP: u8 = 14-pub val PUT_RECORDS: u8 = 15-pub val UPDATE_REFS: u8 = 16-pub val UPDATE_REFS_OK: u8 = 17-pub val RECORDS: u8 = 18-pub val END: u8 = 19-pub val ERROR: u8 = 20--pub val ERR_UNSUPPORTED_VERSION: u8 = 1-pub val ERR_BAD_FRAME: u8 = 2-pub val ERR_NOT_FOUND: u8 = 3-pub val ERR_HASH_MISMATCH: u8 = 4-pub val ERR_NON_CANONICAL: u8 = 5-pub val ERR_MISSING_CLOSURE: u8 = 6-pub val ERR_REF_CONFLICT: u8 = 7-pub val ERR_REJECTED: u8 = 8-pub val ERR_INTERNAL: u8 = 9-pub val ERR_UNAUTHENTICATED: u8 = 10-pub val ERR_FORBIDDEN: u8 = 11-pub val ERR_AUTH_FAILED: u8 = 12-pub val ERR_QUOTA: u8 = 13-pub val ERR_TOO_LARGE: u8 = 14--pub type Frame = {- kind: mut u8- request_id: mut u32- payload: mut bytes.Bytes- base: mut bytes.Bytes-}--pub fn free_frame(f: Frame) void = trust {- if f.base.ptr != none {- bytes.free_ptr(f.base.ptr)- }-}--fn read_exact(s: stream.Stream, out: ref u8, n: usize) bool = trust {- val got: mut usize = 0- for got < n {- val r: i64 = stream.read(s, @ptradd(out, got as i64) as ref u8, n - got)- if r <= 0 {- return false- }- got = got + r as usize- }- return true-}--fn read_u32_be(s: stream.Stream) option[u32] = trust {- val b: ref u8 = @alloc(4) as ref u8- if !read_exact(s, b, 4) {- @free(b as ref void)- return none- }- val v: u32 = ((@load8(b) as u32) << 24)- | ((@load8(@ptradd(b, 1)) as u32) << 16)- | ((@load8(@ptradd(b, 2)) as u32) << 8)- | (@load8(@ptradd(b, 3)) as u32)- @free(b as ref void)- return some v-}--fn put_u32_be(out: ref u8, v: u32) void = trust {- @store8(out, ((v >> 24) & 255) as u8)- @store8(@ptradd(out, 1), ((v >> 16) & 255) as u8)- @store8(@ptradd(out, 2), ((v >> 8) & 255) as u8)- @store8(@ptradd(out, 3), (v & 255) as u8)-}--/// Read one frame. Frames larger than MAX_FRAME are rejected.-pub fn read_frame(s: stream.Stream) option[Frame] = trust {- val len_opt = read_u32_be(s)- val len: mut u32 = 0- match len_opt {- some v => {- len = v- }- none => {- return none- }- }- if len < 5 || len as usize > MAX_FRAME {- return none- }- val body: ref u8 = @alloc(len as usize) as ref u8- if !read_exact(s, body, len as usize) {- @free(body as ref void)- return none- }- val kind: u8 = @load8(body)- val rid: u32 = ((@load8(@ptradd(body, 1)) as u32) << 24)- | ((@load8(@ptradd(body, 2)) as u32) << 16)- | ((@load8(@ptradd(body, 3)) as u32) << 8)- | (@load8(@ptradd(body, 4)) as u32)- val payload: mut bytes.Bytes = bytes.empty()- if len == 5 {- return some Frame{- kind: kind,- request_id: rid,- payload: bytes.empty(),- base: bytes.bytes(body, len as usize)- }- }- payload = bytes.bytes(@ptradd(body, 5), (len - 5) as usize)- return some Frame{- kind: kind,- request_id: rid,- payload: payload,- base: bytes.bytes(body, len as usize)- }-}--/// Write one frame and release `payload`.-pub fn write_frame(- s: stream.Stream,- kind: u8,- request_id: u32,- payload: bytes.Bytes-) bool = trust {- val total: u32 = 5 as u32 + payload.len as u32- val head: ref u8 = @alloc(5) as ref u8- put_u32_be(head, total)- @store8(@ptradd(head, 4), kind)- val header_bytes: bytes.Bytes = bytes.bytes(head, 5)- val rid: ref u8 = @alloc(4) as ref u8- put_u32_be(rid, request_id)- val passed: bool = stream.write_all(s, header_bytes)- && stream.write_all(s, bytes.bytes(rid, 4))- && stream.write_all(s, payload)- @free(head as ref void)- @free(rid as ref void)- if payload.ptr != none {- bytes.free_owned(payload)- }- return passed-}--pub fn write_simple(s: stream.Stream, kind: u8, request_id: u32) bool = trust {- return write_frame(s, kind, request_id, bytes.empty())-}--pub fn write_error(- s: stream.Stream,- request_id: u32,- code: u8,- message: bytes.Bytes-) bool = trust {- val b: mut buf.Buf = buf.new(64)- buf.Buf.put_u8(b, code)- buf.Buf.put_length_prefixed(b, message)- val out: bytes.Bytes = bytes.Bytes.dup(buf.Buf.view(b))- buf.Buf.free(b)- return write_frame(s, ERROR, request_id, out)-}--pub fn read_error(payload: bytes.Bytes) u8 = {- if payload.len == 0 {- return ERR_INTERNAL- }- return bytes.Bytes.at(payload, 0)-}--/// Decode the human-readable part of an ERROR payload. The returned bytes are-/// owned by the caller.-pub fn error_message(payload: bytes.Bytes) bytes.Bytes = trust {- if payload.len < 2 {- return bytes.empty()- }- val r: mut reader.Reader = reader.new(- @ptradd(payload.ptr, 1) as ref u8,- payload.len - 1- )- val decoded = reader.Reader.read_bytes(r, 4096)- match decoded {- ok v => {- return bytes.Bytes.dup(v)- }- err _ => {- return bytes.empty()- }- }-}--pub fn put_bytes_list(b: mut buf.Buf, xs: list[bytes.Bytes]) void = trust {- buf.Buf.put_varint(b, @len(xs) as u64)- for x in xs {- buf.Buf.put_length_prefixed(b, x)- }-}--pub fn put_id_list(b: mut buf.Buf, xs: list[bytes.Bytes]) void = trust {- buf.Buf.put_varint(b, @len(xs) as u64)- for x in xs {- buf.Buf.put_raw(b, x.ptr, 32)- }-}--pub fn read_bytes_list(- data: bytes.Bytes,- max: usize-) result[list[bytes.Bytes], derr.DecodeError] = trust {- val r: mut reader.Reader = reader.new(data.ptr, data.len)- val n: usize = reader.Reader.read_list_len(r, max)?- val out: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()- val i: mut usize = 0- for i < n {- val v: bytes.Bytes = reader.Reader.read_bytes(r, MAX_FRAME)?- @append(out, bytes.Bytes.dup(v))- i++- }- reader.Reader.finish(r)?- return ok out-}--pub fn read_id_list(- data: bytes.Bytes,- max: usize-) result[list[bytes.Bytes], derr.DecodeError] = trust {- val r: mut reader.Reader = reader.new(data.ptr, data.len)- val n: usize = reader.Reader.read_list_len(r, max)?- val out: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()- val i: mut usize = 0- for i < n {- val p: ref u8 = reader.Reader.read_id(r)?- val copy: ref u8 = @alloc(32) as ref u8- @memcpy(copy as ref void, p as ref void, 32)- @append(out, bytes.bytes(copy, 32))- i++- }- reader.Reader.finish(r)?- return ok out-}--pub fn free_bytes_list(xs: list[bytes.Bytes]) void = trust {- for x in xs {- if x.ptr != none {- bytes.free_owned(x)- }- }- @listfree(xs)-}--test "error payloads expose code and message" {- trust {- val b: mut buf.Buf = buf.new(64)- buf.Buf.put_u8(b, ERR_FORBIDDEN)- buf.Buf.put_length_prefixed(b, bytes.bytes(c"write role required", 19))- val payload: bytes.Bytes = bytes.Bytes.dup(buf.Buf.view(b))- assert read_error(payload) == ERR_FORBIDDEN- val message: bytes.Bytes = error_message(payload)- assert bytes.Bytes.eql(message, bytes.bytes(c"write role required", 19))- bytes.free_owned(message)- bytes.free_owned(payload)- buf.Buf.free(b)- }-}--- a/veins/src/server/quota.sx+++ /dev/null@@ -1,113 +0,0 @@-/// Per-namespace storage accounting for `vn serve -quota`.--val fs = use("std/fs")-val str = use("std/string")-val time = use("std/time")-val bytes = use("../core/bytes.sx")-val files = use("../io/files.sx")--fn first_component(name: bytes.Bytes) bytes.Bytes = trust {- val i: mut usize = 0- for i < name.len {- if bytes.Bytes.at(name, i) == 47 {- return bytes.Bytes.slice(name, 0, i)- }- i++- }- return name-}--/// `root/<first path component of the repository name>`.-pub fn namespace_path(root: str.StringView, repo_name: bytes.Bytes) str.StringView = trust {- val ns: bytes.Bytes = first_component(repo_name)- return files.join(root, str.view(ns.ptr, ns.len as i64))-}--fn tree_size(dir: str.StringView) u64 = trust {- val total: mut u64 = 0- val names: list[ref u8] = files.list_dir(dir)- for n in names {- val child: str.StringView = files.join(dir, str.from_cstr(n))- if files.exists_dir(child) {- total = total + tree_size(child)- } else {- val size = fs.file_size(child)- if size is some nbytes {- if nbytes > 0 {- total = total + nbytes as u64- }- }- }- files.free_path(child)- }- files.free_names(names)- return total-}--fn repo_size(dir: str.StringView) u64 = trust {- val packs: str.StringView = files.join(dir, str.from_cstr(c".veins/store/packs"))- val total: mut u64 = 0- if files.exists_dir(packs) {- total = tree_size(packs)- }- files.free_path(packs)- return total-}--/// Sum the persistent pack and index bytes for a repository or for every-/// immediate repository under a namespace directory.-pub fn used(dir: str.StringView) u64 = trust {- if !files.exists_dir(dir) {- return 0- }- val own: u64 = repo_size(dir)- if own > 0 {- return own- }- val total: mut u64 = 0- val names: list[ref u8] = files.list_dir(dir)- for n in names {- val child: str.StringView = files.join(dir, str.from_cstr(n))- if files.exists_dir(child) {- total = total + repo_size(child)- }- files.free_path(child)- }- files.free_names(names)- return total-}--test "storage usage sums namespace repositories" {- trust {- val base: str.StringView = str.from_cstr(fs.temp_dir_cstr())- val name_c: ref u8 = @fmtalloc("veins-quota-{d}", {time.now_ns()})- val name: str.StringView = str.from_cstr(name_c)- val root: str.StringView = files.join(base, name)- @free(name_c as ref void)- assert files.mkdir_all(root)- val owner: str.StringView = files.join(root, str.from_cstr(c"alice"))- assert files.mkdir_all(owner)- val repo: str.StringView = files.join(owner, str.from_cstr(c"repo"))- assert files.mkdir_all(repo)- val veins: str.StringView = files.join(repo, str.from_cstr(c".veins"))- assert files.mkdir_all(veins)- val store: str.StringView = files.join(veins, str.from_cstr(c"store"))- assert files.mkdir_all(store)- val packs: str.StringView = files.join(store, str.from_cstr(c"packs"))- assert files.mkdir_all(packs)- val pack: str.StringView = files.join(packs, str.from_cstr(c"a.vpack"))- val index: str.StringView = files.join(packs, str.from_cstr(c"a.vidx"))- assert files.write_all(pack, bytes.bytes(c"abc", 3))- assert files.write_all(index, bytes.bytes(c"defgh", 5))- assert used(owner) == 8- files.free_path(index)- files.free_path(pack)- files.free_path(packs)- files.free_path(store)- files.free_path(veins)- files.free_path(repo)- files.free_path(owner)- val _ = fs.remove_dir_all(root)- files.free_path(root)- }-}--- a/veins/src/server/serve.sx+++ /dev/null@@ -1,1688 +0,0 @@-/// Native veins server: stdio and TLS transports.--val stdio = use("std/stdio")-val str = use("std/string")-val cmsg = use("../core/msg.sx")-val reader = use("../core/reader.sx")-val random = use("std/crypto/random")-val time = use("std/time")-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 types = use("../object/types.sx")-val tree = use("../object/tree.sx")-val blob = use("../object/blob.sx")-val conflict = use("../object/conflict.sx")-val commit = use("../object/commit.sx")-val view = use("../object/view.sx")-val graph = use("../object/graph.sx")-val store = use("../store/store.sx")-val state = use("../store/state.sx")-val layout = use("../store/layout.sx")-val idmap = use("../store/idmap.sx")-val writer = use("../store/writer.sx")-val txnmod = use("../store/txn.sx")-val viewops = use("../store/viewops.sx")-val zstd = use("../store/zstd.sx")-val files = use("../io/files.sx")-val stream = use("../net/stream.sx")-val net = use("std/net")-val allocators = use("std/allocators")-val runtime = use("std/runtime")-val wire = use("../protocol/wire.sx")-val msg = use("../protocol/messages.sx")-val ed = use("../crypto/ed25519.sx")-val tls = use("../crypto/tls.sx")-val access = use("../auth/access.sx")-val handshake = use("../auth/handshake.sx")-val b3 = use("../crypto/blake3.sx")-val quota = use("quota.sx")--val MAX_CHUNKS_PER_REQUEST: usize = 4096-val MAX_PUSH_RECORDS: usize = 100000-val QUOTA_RESERVE: u64 = 1048576-val DRAIN_BYTES: usize = 67108864--type Session = {- s: mut stream.Stream- repo: mut layout.Repo- repo_present: mut bool- handles: mut list[ref store.Handle]- store_open: mut bool- access: mut access.Access- hello_repo: mut bytes.Bytes- server_nonce: mut bytes.Bytes- client_nonce: mut bytes.Bytes- binding: mut bytes.Bytes- version: mut u16- authed: mut bool- role: mut u8- public_key: mut bytes.Bytes- fingerprint: mut bytes.Bytes- haves: mut list[bytes.Bytes]- quota_bytes: mut u64- quota_dir: mut str.StringView- failed_auth: mut i32- closing: 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)-}--/// A client disappearing mid-write must not take the whole server down.-/// Without a handler, POSIX delivers SIGPIPE and the default action terminates-/// the process, which looks like an unexplained connection drop to everyone-/// else. Returning from the handler lets the write fail with EPIPE instead.-fn ignore_sigpipe(_: i32) void = trust {- return-}--fn free_bytes_list(xs: list[bytes.Bytes]) void = trust {- for x in xs {- if x.ptr != none {- bytes.free_owned(x)- }- }- @listfree(xs)-}--fn effective_role(s: ref Session) u8 = trust {- if s.authed {- return s.role- }- if s.access.valid && s.access.anonymous_read && s.repo_present {- return access.ROLE_READ- }- return access.ROLE_ANONYMOUS-}--fn deny(s: mut ref Session, rid: u32, write: bool) bool = trust {- val role: u8 = effective_role(s)- if write {- if role == access.ROLE_WRITE {- return false- }- if !s.authed {- wire.write_error(- s.s,- rid,- wire.ERR_UNAUTHENTICATED,- bytes.bytes(c"authentication required", 23)- )- } else {- wire.write_error(s.s, rid, wire.ERR_FORBIDDEN, bytes.bytes(c"write role required", 19))- }- return true- }- if role == access.ROLE_READ || role == access.ROLE_WRITE {- return false- }- if !s.authed {- wire.write_error(- s.s,- rid,- wire.ERR_UNAUTHENTICATED,- bytes.bytes(c"authentication required", 23)- )- } else {- wire.write_error(s.s, rid, wire.ERR_FORBIDDEN, bytes.bytes(c"read role required", 18))- }- return true-}--fn log_line(s: ref Session, text: bytes.Bytes) void = trust {- if !s.repo_present {- return- }- val dir: str.StringView = layout.veins_dir(s.repo)- val p: str.StringView = files.join(dir, str.from_cstr(c"server.log"))- files.append_all(p, text)- files.free_path(p)- files.free_path(dir)-}--fn log_outcome(s: mut ref Session, outcome: bytes.Bytes) void = trust {- if !s.repo_present {- return- }- val who: bytes.Bytes = handshake.role_name(effective_role(s))- val line: ref u8 = @fmtalloc(- "{d} {s} {s} {s}\n",- {- time.unix_now_millis(),- str.view(who.ptr, who.len as i64),- str.view(outcome.ptr, outcome.len as i64),- str.view(s.hello_repo.ptr, s.hello_repo.len as i64)- }- )- log_line(s, bytes.from_cstr(line))- @free(line as ref void)-}--fn safe_repo_name(name: bytes.Bytes) bool = trust {- if name.len == 0 || name.len > 4096 {- return false- }- if bytes.Bytes.at(name, 0) == 47 {- return false- }- val i: mut usize = 0- for i < name.len {- val c: u8 = bytes.Bytes.at(name, i)- if c == 0 || c == 92 {- return false- }- i++- }- // Reject any path component equal to "..".- val start: mut usize = 0- val j: mut usize = 0- for j <= name.len {- if j == name.len || bytes.Bytes.at(name, j) == 47 {- if j - start == 2- && bytes.Bytes.at(name, start) == 46- && bytes.Bytes.at(name, start + 1) == 46 {- return false- }- start = j + 1- }- j++- }- return true-}--fn open_session_store(s: mut ref Session) void = trust {- if s.store_open {- return- }- val st: store.Store = store.open_all(s.repo)- s.handles = st.handles- s.store_open = true-}--fn select_repo(s: mut ref Session, root: option[layout.Repo]) void = trust {- if s.repo_present {- return- }- if root is some r {- if !safe_repo_name(s.hello_repo) {- return- }- val joined: str.StringView = files.join(- layout.root_view(r),- str.view(s.hello_repo.ptr, s.hello_repo.len as i64)- )- val found = layout.discover(joined)- files.free_path(joined)- if found is some repo {- s.repo = repo- s.repo_present = true- if s.quota_bytes > 0 {- files.free_path(s.quota_dir)- s.quota_dir = quota.namespace_path(layout.root_view(r), s.hello_repo)- }- }- }-}--fn read_body(s: mut ref Session, id: objid.Id, kind: u8) option[bytes.Bytes] = trust {- return state.read_body(s.handles, id, kind)-}--fn make_record(id: objid.Id, kind: u8, body: bytes.Bytes) bytes.Bytes = trust {- val b: mut buf.Buf = buf.new(body.len + 64)- buf.Buf.put_raw(b, id.ptr, 32)- buf.Buf.put_u8(b, kind)- buf.Buf.put_u8(b, 0)- buf.Buf.put_varint(b, body.len as u64)- buf.Buf.put_varint(b, body.len as u64)- buf.Buf.put_bytes(b, body)- val out: bytes.Bytes = bytes.Bytes.dup(buf.Buf.view(b))- buf.Buf.free(b)- return out-}--type SendState = {- s: mut ref Session- rid: mut u32- hash: mut ref void- failed: mut bool-}--fn send_record_id(ss: mut ref SendState, id: objid.Id, kind: u8, body: bytes.Bytes) bool = trust {- val rec: bytes.Bytes = make_record(id, kind, body)- if ss.hash != none {- b3.hasher_update(ss.hash, rec.ptr, rec.len)- }- return wire.write_frame(ss.s.s, wire.RECORDS, ss.rid, rec)-}--fn send_end(ss: mut ref SendState) bool = trust {- val digest: ref u8 = @alloc(32) as ref u8- b3.hasher_final(ss.hash, digest)- val out: bytes.Bytes = bytes.bytes(digest, 32)- val passed: bool = wire.write_frame(ss.s.s, wire.END, ss.rid, out)- return passed-}--fn collect_tree(- ss: mut ref SendState,- id: objid.Id,- seen: mut idmap.IdSet,- send: bool-) void = trust {- if !idmap.put(seen, copy_id_bytes(id)) {- return- }- val body_opt = read_body(ss.s, id, types.TREE)- val body: mut bytes.Bytes = bytes.empty()- match body_opt {- some b => {- body = b- }- none => {- ss.failed = true- return- }- }- if send {- if !send_record_id(ss, id, types.TREE, body) {- ss.failed = true- }- }- val decoded = tree.decode(body)- match decoded {- ok t => {- for e in t.entries {- if e.kind == tree.KIND_SUBTREE {- collect_tree(ss, e.target, seen, send)- } elif e.kind == tree.KIND_CONFLICT {- collect_object(ss, e.target, types.CONFLICT, seen, send)- } elif e.kind != tree.KIND_SUBMODULE {- collect_object(ss, e.target, types.BLOB, seen, send)- }- }- tree.free_tree(t)- }- err _ => {- ss.failed = true- }- }- files.free_buffer(body)-}--fn collect_object(- ss: mut ref SendState,- id: objid.Id,- kind: u8,- seen: mut idmap.IdSet,- send: bool-) void = trust {- if !idmap.put(seen, copy_id_bytes(id)) {- return- }- val body_opt = read_body(ss.s, id, kind)- val body: mut bytes.Bytes = bytes.empty()- match body_opt {- some b => {- body = b- }- none => {- ss.failed = true- return- }- }- if send {- if !send_record_id(ss, id, kind, body) {- ss.failed = true- }- }- if kind == types.BLOB {- val dec = blob.decode(body)- if dec is ok b {- if b.form == blob.FORM_INTERIOR {- for e in b.entries {- collect_object(ss, e.id, types.BLOB, seen, send)- }- }- blob.free_blob(b)- } else {- ss.failed = true- }- } elif kind == types.CONFLICT {- val dec2 = conflict.decode(body)- if dec2 is ok c {- for v in c.adds {- if v.target.ptr != none {- val child_kind: u8 = value_kind_to_type(v.kind)- if child_kind != 0 {- collect_object(ss, v.target, child_kind, seen, send)- }- }- }- for v in c.removes {- if v.target.ptr != none {- val child_kind2: u8 = value_kind_to_type(v.kind)- if child_kind2 != 0 {- collect_object(ss, v.target, child_kind2, seen, send)- }- }- }- conflict.free_conflict(c)- } else {- ss.failed = true- }- }- files.free_buffer(body)-}--fn value_kind_to_type(kind: u8) u8 = {- if kind == tree.KIND_SUBTREE {- return types.TREE- }- if kind == tree.KIND_CONFLICT {- return types.CONFLICT- }- if kind == tree.KIND_FILE || kind == tree.KIND_EXECUTABLE || kind == tree.KIND_SYMLINK {- return types.BLOB- }- return 0-}--fn copy_id_bytes(id: objid.Id) bytes.Bytes = trust {- return bytes.bytes(id.ptr, 32)-}--fn handle_hello(s: mut ref Session, f: wire.Frame, root: option[layout.Repo]) bool = trust {- val dec = msg.decode_hello(f.payload)- val h: mut msg.Hello = msg.Hello{- min_version: 0,- max_version: 0,- capabilities: lists.new[bytes.Bytes](),- repo: bytes.empty(),- client_nonce: bytes.empty()- }- match dec {- ok v => {- h = v- }- err _ => {- wire.write_error(s.s, f.request_id, wire.ERR_BAD_FRAME, bytes.bytes(c"bad HELLO", 9))- return false- }- }- if h.min_version > msg.PROTOCOL_VERSION || h.max_version < msg.PROTOCOL_VERSION {- wire.write_error(- s.s,- f.request_id,- wire.ERR_UNSUPPORTED_VERSION,- bytes.bytes(c"no common version", 17)- )- msg.free_hello(h)- return false- }- s.version = msg.PROTOCOL_VERSION- if s.hello_repo.ptr != none {- bytes.free_ptr(s.hello_repo.ptr)- }- s.hello_repo = bytes.Bytes.dup(h.repo)- if s.client_nonce.ptr != none {- bytes.free_ptr(s.client_nonce.ptr)- }- s.client_nonce = bytes.Bytes.dup(h.client_nonce)- select_repo(s, root)- if !s.repo_present && s.hello_repo.len > 0 {- cmsg.error_prefix()- stdio.eprint(- "repository not found: {s}\n",- {str.view(s.hello_repo.ptr, s.hello_repo.len as i64)}- )- wire.write_error(- s.s,- f.request_id,- wire.ERR_NOT_FOUND,- bytes.bytes(c"repository not found", 20)- )- msg.free_hello(h)- return false- }- if s.repo_present {- s.access = access.load(s.repo)- if !s.access.valid {- cmsg.error_prefix()- stdio.eprint(- "access file error at line {d} in {s}\n",- {s.access.error_line, layout.root_view(s.repo)}- )- wire.write_error(- s.s,- f.request_id,- wire.ERR_INTERNAL,- bytes.bytes(c"invalid access file", 19)- )- msg.free_hello(h)- return false- }- open_session_store(s)- }- log_outcome(s, bytes.bytes(c"hello", 5))- val nonce: ref u8 = @alloc(32) as ref u8- random.random_bytes(nonce as ref void, 32)- s.server_nonce = bytes.bytes(nonce, 32)- val caps: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()- @append(caps, bytes.Bytes.dup(bytes.bytes(c"zstd-records", 12)))- @append(caps, bytes.Bytes.dup(bytes.bytes(c"lazy-chunks", 11)))- @append(caps, bytes.Bytes.dup(bytes.bytes(c"push", 4)))- @append(caps, bytes.Bytes.dup(bytes.bytes(c"auth-ed25519", 12)))- val auth_required: mut u8 = 1- if s.repo_present && s.access.anonymous_read {- auth_required = 0- }- val fine: msg.HelloOk = msg.HelloOk{- version: s.version,- capabilities: caps,- server_nonce: s.server_nonce,- auth_required: auth_required- }- val body: bytes.Bytes = msg.encode_hello_ok(fine)- val wrote: bool = wire.write_frame(s.s, wire.HELLO_OK, f.request_id, body)- free_caps(caps)- msg.free_hello(h)- return wrote-}--fn free_caps(caps: list[bytes.Bytes]) void = trust {- for c in caps {- if c.ptr != none {- bytes.free_owned(c)- }- }- @listfree(caps)-}--fn handle_auth(s: mut ref Session, f: wire.Frame) bool = trust {- if s.authed {- wire.write_error(s.s, f.request_id, wire.ERR_BAD_FRAME, bytes.bytes(c"repeated AUTH", 13))- s.closing = true- return false- }- val dec = msg.decode_auth(f.payload)- val a: mut msg.Auth = msg.Auth{public_key: bytes.empty(), signature: bytes.empty()}- match dec {- ok v => {- a = v- }- err _ => {- s.failed_auth++- wire.write_error(- s.s,- f.request_id,- wire.ERR_AUTH_FAILED,- bytes.bytes(c"authentication failed", 21)- )- if s.failed_auth >= 3 {- s.closing = true- }- return true- }- }- val role: mut u8 = 255- if s.repo_present && s.access.valid {- role = access.role_for(s.access, a.public_key)- }- val message: bytes.Bytes = handshake.auth_message(- s.version,- s.hello_repo,- s.server_nonce,- s.client_nonce,- s.binding- )- val sig_ok: bool = role != 255 && ed.verify(a.public_key, message, a.signature)- bytes.free_owned(message)- if !sig_ok {- s.failed_auth++- wire.write_error(- s.s,- f.request_id,- wire.ERR_AUTH_FAILED,- bytes.bytes(c"authentication failed", 21)- )- if a.public_key.ptr != none {- bytes.free_ptr(a.public_key.ptr)- }- if a.signature.ptr != none {- bytes.free_ptr(a.signature.ptr)- }- if s.failed_auth >= 3 {- s.closing = true- }- return true- }- val fp_opt = ed.fingerprint_bytes(a.public_key)- val fp: mut bytes.Bytes = bytes.empty()- if fp_opt is some v {- fp = v- }- s.authed = true- s.role = role- s.public_key = bytes.Bytes.dup(a.public_key)- s.fingerprint = fp- val fine: msg.AuthOk = msg.AuthOk{role: role, fingerprint: fp}- val body: bytes.Bytes = msg.encode_auth_ok(fine)- val wrote: bool = wire.write_frame(s.s, wire.AUTH_OK, f.request_id, body)- if a.public_key.ptr != none {- bytes.free_ptr(a.public_key.ptr)- }- if a.signature.ptr != none {- bytes.free_ptr(a.signature.ptr)- }- log_outcome(s, bytes.bytes(c"auth-ok", 7))- return wrote-}--fn handle_whoami(s: mut ref Session, f: wire.Frame) bool = trust {- val role: u8 = effective_role(s)- val b: mut buf.Buf = buf.new(64)- buf.Buf.put_u8(b, role)- buf.Buf.put_length_prefixed(b, s.fingerprint)- val out: bytes.Bytes = bytes.Bytes.dup(buf.Buf.view(b))- buf.Buf.free(b)- return wire.write_frame(s.s, wire.WHOAMI_OK, f.request_id, out)-}--fn change_id_of(s: mut ref Session, id: objid.Id) bytes.Bytes = trust {- val lc_opt = graph.load_commit(s.handles, id)- if lc_opt is some lc {- val out: bytes.Bytes = bytes.Bytes.dup(- bytes.bytes(lc.c.change_id.ptr, 16)- )- graph.free_loaded(lc)- return out- }- return bytes.empty()-}--fn handle_list_refs(s: mut ref Session, f: wire.Frame) bool = trust {- if deny(s, f.request_id, false) {- return true- }- // Log before reading state: if the process dies while assembling the- // response, this line (without a matching "close") localises the failure.- log_outcome(s, bytes.bytes(c"list-refs", 9))- val v_opt = state.current_view(s.repo, s.handles)- val v: mut ref view.View = none- match v_opt {- some x => {- v = x- }- none => {- // No operation heads is a legitimate empty repository. Anything- // else is an unreadable state; answer with an error frame instead- // of silently pretending the repository is empty.- val hs: list[objid.Id] = state.heads(s.repo)- val have_heads: bool = @len(hs) > 0- for h in hs {- if h.ptr != none {- val hp: mut ref void = h.ptr as ref void- @free(hp)- }- }- @listfree(hs)- if have_heads {- wire.write_error(- s.s,- f.request_id,- wire.ERR_INTERNAL,- bytes.bytes(c"cannot read operation state", 27)- )- log_outcome(s, bytes.bytes(c"list-refs-error", 15))- return true- }- v = state.empty_view()- }- }- val out: mut list[msg.RefInfo] = lists.new[msg.RefInfo]()- for bm in v.bookmarks {- if @len(bm.targets.adds) == 1 {- val o = @get(bm.targets.adds, 0)- if o is some target {- if target.ptr != none {- @append(- out,- msg.RefInfo{- name: bytes.Bytes.dup(bm.name),- target: bytes.Bytes.dup(bytes.bytes(target.ptr, 32)),- change_id: change_id_of(s, target),- kind: 0- }- )- }- }- }- }- for t in v.tags {- if t.target.ptr != none {- @append(- out,- msg.RefInfo{- name: bytes.Bytes.dup(t.name),- target: bytes.Bytes.dup(bytes.bytes(t.target.ptr, 32)),- change_id: change_id_of(s, t.target),- kind: 1- }- )- }- }- view.free_view(v)- val body: bytes.Bytes = msg.encode_refs(out)- msg.free_refs(out)- val wrote: bool = wire.write_frame(s.s, wire.REFS, f.request_id, body)- if !wrote {- log_outcome(s, bytes.bytes(c"list-refs-write-error", 21))- }- return wrote-}--fn handle_negotiate(s: mut ref Session, f: wire.Frame) bool = trust {- if deny(s, f.request_id, false) {- return true- }- val dec = msg.decode_negotiate(f.payload)- val wants: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()- val haves: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()- match dec {- ok v => {- wants = v.wants- haves = v.haves- }- err _ => {- wire.write_error(- s.s,- f.request_id,- wire.ERR_BAD_FRAME,- bytes.bytes(c"bad NEGOTIATE", 13)- )- return true- }- }- free_bytes_list(s.haves)- s.haves = lists.new[bytes.Bytes]()- val known: mut list[u64] = lists.new[u64]()- val any_known: mut bool = false- for h in haves {- val found: mut bool = false- val loc: mut store.Loc = store.Loc{pack_index: 0, record_index: 0, kind: 0}- if store.find_handles(s.handles, objid.id(h.ptr), loc) {- found = true- any_known = true- }- val bit: mut u64 = 0- if found {- bit = 1- }- @append(known, bit)- @append(s.haves, bytes.Bytes.dup(h))- }- val enough: mut u8 = 0- if @len(haves) == 0 || any_known {- enough = 1- }- val body: bytes.Bytes = msg.encode_negotiate_ok(known, enough)- @listfree(known)- free_bytes_list(wants)- free_bytes_list(haves)- return wire.write_frame(s.s, wire.NEGOTIATE_OK, f.request_id, body)-}--fn handle_fetch(s: mut ref Session, f: wire.Frame) bool = trust {- if deny(s, f.request_id, false) {- return true- }- val dec = msg.decode_ids(f.payload, 1000000)- val wants: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()- match dec {- ok v => {- wants = v- }- err _ => {- wire.write_error(s.s, f.request_id, wire.ERR_BAD_FRAME, bytes.bytes(c"bad wants", 9))- return true- }- }- if @len(wants) == 0 {- wire.write_error(s.s, f.request_id, wire.ERR_BAD_FRAME, bytes.bytes(c"empty wants", 11))- free_bytes_list(wants)- return true- }- val want_ids: mut list[objid.Id] = lists.new[objid.Id]()- for w in wants {- @append(want_ids, objid.id(w.ptr))- }- val all: list[objid.Id] = graph.collect(s.handles, want_ids)- val exclude: mut idmap.IdSet = idmap.new(64)- for h in s.haves {- val hs: mut list[objid.Id] = lists.new[objid.Id]()- @append(hs, objid.id(h.ptr))- val hc = graph.collect(s.handles, hs)- for x in hc {- idmap.put(exclude, copy_id_bytes(x))- }- graph.free_ids(hc)- @listfree(hs)- }- val ss_hash: ref void = @alloc(b3.hasher_state_size()) as ref void- b3.hasher_init(ss_hash)- val ss: mut SendState = SendState{s: s, rid: f.request_id, hash: ss_hash, failed: false}- val seen: mut idmap.IdSet = idmap.new(256)- val i: mut usize = 0- for i < @len(all) {- val o = @get(all, i)- if o is some cid {- if !idmap.contains(exclude, copy_id_bytes(cid)) {- val lc_opt = graph.load_commit(s.handles, cid)- if lc_opt is some lc {- if !send_record_id(ss, cid, types.COMMIT, lc.body) {- ss.failed = true- }- collect_tree(ss, lc.c.root_tree, seen, true)- graph.free_loaded(lc)- } else {- ss.failed = true- }- }- }- i++- }- if !ss.failed {- send_end(ss)- }- @free(ss_hash)- idmap.free(seen)- idmap.free(exclude)- graph.free_ids(all)- @listfree(want_ids)- free_bytes_list(wants)- log_outcome(s, bytes.bytes(c"fetch", 5))- return !ss.failed-}--fn handle_get_chunks(s: mut ref Session, f: wire.Frame) bool = trust {- if deny(s, f.request_id, false) {- return true- }- val dec = msg.decode_ids(f.payload, MAX_CHUNKS_PER_REQUEST)- val ids: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()- match dec {- ok v => {- ids = v- }- err _ => {- wire.write_error(- s.s,- f.request_id,- wire.ERR_BAD_FRAME,- bytes.bytes(c"bad chunk list", 14)- )- return true- }- }- val ss_hash: ref void = @alloc(b3.hasher_state_size()) as ref void- b3.hasher_init(ss_hash)- val ss: mut SendState = SendState{s: s, rid: f.request_id, hash: ss_hash, failed: false}- for id in ids {- val loc: mut store.Loc = store.Loc{pack_index: 0, record_index: 0, kind: 0}- if !store.find_handles(s.handles, objid.id(id.ptr), loc) || loc.kind != types.CHUNK {- ss.failed = true- break- }- val body_opt = store.get_handles(s.handles, loc)- if body_opt is ok body {- if !send_record_id(ss, objid.id(id.ptr), types.CHUNK, body) {- ss.failed = true- }- files.free_buffer(body)- } else {- ss.failed = true- }- }- if ss.failed {- wire.write_error(s.s, f.request_id, wire.ERR_NOT_FOUND, bytes.bytes(c"chunk not found", 15))- } else {- send_end(ss)- }- @free(ss_hash)- free_bytes_list(ids)- return !ss.failed-}--fn handle_have_query(s: mut ref Session, f: wire.Frame) bool = trust {- if deny(s, f.request_id, true) {- return true- }- val dec = msg.decode_ids(f.payload, 1000000)- val ids: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()- match dec {- ok v => {- ids = v- }- err _ => {- wire.write_error(- s.s,- f.request_id,- wire.ERR_BAD_FRAME,- bytes.bytes(c"bad HAVE_QUERY", 14)- )- return true- }- }- val bits: mut list[u64] = lists.new[u64]()- for id in ids {- val loc: mut store.Loc = store.Loc{pack_index: 0, record_index: 0, kind: 0}- val bit: mut u64 = 0- if store.find_handles(s.handles, objid.id(id.ptr), loc) {- bit = 1- }- @append(bits, bit)- }- val body: bytes.Bytes = msg.encode_bitmap(bits)- @listfree(bits)- free_bytes_list(ids)- return wire.write_frame(s.s, wire.HAVE_BITMAP, f.request_id, body)-}--type IncomingRecord = {- id: mut bytes.Bytes- kind: mut u8- body: mut bytes.Bytes-}--fn parse_record(data: bytes.Bytes) option[IncomingRecord] = trust {- if data.len < 35 {- return none- }- val r: mut reader.Reader = reader.new(data.ptr, data.len)- val idp: ref u8 = reader.Reader.read_id(r)?- val kind: u8 = reader.Reader.read_u8(r)?- val comp: u8 = reader.Reader.read_u8(r)?- val raw_len: u64 = reader.Reader.read_varint(r)?- val stored_len: u64 = reader.Reader.read_varint(r)?- if raw_len == 0 || raw_len > 67108864 {- return none- }- val stored: bytes.Bytes = reader.Reader.read_raw(r, stored_len as usize)?- if !reader.Reader.at_end(r) {- return none- }- val idcopy: ref u8 = @alloc(32) as ref u8- @memcpy(idcopy as ref void, idp as ref void, 32)- if comp == 0 {- if stored.len != raw_len as usize {- @free(idcopy as ref void)- return none- }- return some IncomingRecord{- id: bytes.bytes(idcopy, 32),- kind: kind,- body: bytes.Bytes.dup(stored)- }- }- val dec = zstd.decompress(stored, raw_len as usize)- if dec is some d {- return some IncomingRecord{- id: bytes.bytes(idcopy, 32),- kind: kind,- body: d- }- }- @free(idcopy as ref void)- return none-}--fn object_exists(handles: list[ref store.Handle], id: objid.Id) bool = trust {- val loc: mut store.Loc = store.Loc{pack_index: 0, record_index: 0, kind: 0}- return store.find_handles(handles, id, loc)-}--fn check_closure(handles: list[ref store.Handle], id: objid.Id, kind: u8) bool = trust {- val body_opt = state.read_body(handles, id, kind)- val body: mut bytes.Bytes = bytes.empty()- if body_opt is some b {- body = b- } else {- return false- }- val fine: mut bool = true- if kind == types.COMMIT {- val dec = commit.decode(body)- if dec is ok c {- if !object_exists(handles, c.root_tree) {- fine = false- }- for p in c.parents {- if !object_exists(handles, p) {- fine = false- }- }- commit.free_commit(c)- } else {- fine = false- }- } elif kind == types.TREE {- val dec = tree.decode(body)- if dec is ok t {- for e in t.entries {- if e.kind != tree.KIND_SUBMODULE && !object_exists(handles, e.target) {- fine = false- }- }- tree.free_tree(t)- } else {- fine = false- }- } elif kind == types.BLOB {- val dec = blob.decode(body)- if dec is ok b {- for e in b.entries {- if !object_exists(handles, e.id) {- fine = false- }- }- blob.free_blob(b)- } else {- fine = false- }- } elif kind == types.CONFLICT {- val dec = conflict.decode(body)- if dec is ok c {- for v in c.adds {- if v.target.ptr != none && !object_exists(handles, v.target) {- fine = false- }- }- for v in c.removes {- if v.target.ptr != none && !object_exists(handles, v.target) {- fine = false- }- }- conflict.free_conflict(c)- } else {- fine = false- }- }- files.free_buffer(body)- return fine-}--fn drain_push(s: ref Session, max_bytes: usize) bool = trust {- val seen: mut usize = 0- for seen <= max_bytes {- val nf = wire.read_frame(s.s)- val fr: mut wire.Frame = wire.Frame{- kind: 0,- request_id: 0,- payload: bytes.empty(),- base: bytes.empty()- }- match nf {- some x => {- fr = x- }- none => {- return false- }- }- val kind: u8 = fr.kind- val size: usize = fr.payload.len- wire.free_frame(fr)- if kind == wire.END {- return true- }- if kind != wire.RECORDS {- return false- }- seen = seen + size- }- return false-}--fn handle_put_records(s: mut ref Session, f: wire.Frame) bool = trust {- if deny(s, f.request_id, true) {- return true- }- val limit: mut u64 = 0- if s.quota_bytes > 0 {- val used: u64 = quota.used(s.quota_dir)- if used + QUOTA_RESERVE >= s.quota_bytes {- if !drain_push(s, DRAIN_BYTES) {- s.closing = true- }- return wire.write_error(- s.s,- f.request_id,- wire.ERR_QUOTA,- bytes.bytes(c"storage quota exceeded", 23)- )- }- limit = s.quota_bytes - used - QUOTA_RESERVE- }- val w_opt = writer.open_limited(s.repo, limit)- val w: mut ref writer.Writer = none- match w_opt {- some x => {- w = x- }- none => {- wire.write_error(s.s, f.request_id, wire.ERR_INTERNAL, bytes.bytes(c"cannot write", 12))- return true- }- }- val hash: ref void = @alloc(b3.hasher_state_size()) as ref void- b3.hasher_init(hash)- val failed: mut bool = false- val too_large: mut bool = false- val quota_hit: mut bool = false- val records: mut usize = 0- val accepted: mut list[objid.Id] = lists.new[objid.Id]()- for {- val nf = wire.read_frame(s.s)- val fr: mut wire.Frame = wire.Frame{- kind: 0,- request_id: 0,- payload: bytes.empty(),- base: bytes.empty()- }- match nf {- some x => {- fr = x- }- none => {- failed = true- break- }- }- if fr.kind == wire.END {- val got: bytes.Bytes = fr.payload- val digest: ref u8 = @alloc(32) as ref u8- b3.hasher_final(hash, digest)- if got.len != 32 || !bytes.Bytes.eql(bytes.bytes(digest, 32), got) {- failed = true- }- @free(digest as ref void)- wire.free_frame(fr)- break- }- if fr.kind != wire.RECORDS {- wire.free_frame(fr)- failed = true- break- }- records++- if records > MAX_PUSH_RECORDS {- too_large = true- failed = true- wire.free_frame(fr)- break- }- b3.hasher_update(hash, fr.payload.ptr, fr.payload.len)- val pr = parse_record(fr.payload)- if pr is some rec {- val computed: objid.Id = objid.object_id(rec.kind, rec.body)- if !objid.Id.eql(computed, objid.id(rec.id.ptr)) {- failed = true- } else {- writer.add_known(w, rec.kind, objid.id(rec.id.ptr), rec.body)- @append(accepted, copy_id(objid.id(rec.id.ptr)))- if w.failed {- quota_hit = w.quota_hit- failed = true- }- }- bytes.free_ptr(computed.ptr)- bytes.free_ptr(rec.id.ptr)- } else {- failed = true- }- wire.free_frame(fr)- if failed {- break- }- }- @free(hash as ref void)- if failed {- val was_quota: bool = quota_hit- writer.abort(w)- if !drain_push(s, DRAIN_BYTES) {- s.closing = true- }- for id in accepted {- if id.ptr != none {- bytes.free_ptr(id.ptr)- }- }- @listfree(accepted)- if too_large {- return wire.write_error(- s.s,- f.request_id,- wire.ERR_TOO_LARGE,- bytes.bytes(c"too many objects in one push", 29)- )- }- if was_quota {- return wire.write_error(- s.s,- f.request_id,- wire.ERR_QUOTA,- bytes.bytes(c"storage quota exceeded", 23)- )- }- return wire.write_error(- s.s,- f.request_id,- wire.ERR_HASH_MISMATCH,- bytes.bytes(c"record rejected", 15)- )- }- val status: i32 = writer.finish(w)- if status != 0 {- for id in accepted {- if id.ptr != none {- bytes.free_ptr(id.ptr)- }- }- @listfree(accepted)- if status == 2 {- return wire.write_error(- s.s,- f.request_id,- wire.ERR_QUOTA,- bytes.bytes(c"storage quota exceeded", 23)- )- }- return wire.write_error(- s.s,- f.request_id,- wire.ERR_INTERNAL,- bytes.bytes(c"pack write failed", 17)- )- }- open_session_store(s)- val closure_ok: mut bool = true- for id in accepted {- val loc: mut store.Loc = store.Loc{pack_index: 0, record_index: 0, kind: 0}- if store.find_handles(s.handles, id, loc) {- if !check_closure(s.handles, id, loc.kind) {- closure_ok = false- break- }- }- }- for id in accepted {- if id.ptr != none {- bytes.free_ptr(id.ptr)- }- }- @listfree(accepted)- if !closure_ok {- return wire.write_error(- s.s,- f.request_id,- wire.ERR_MISSING_CLOSURE,- bytes.bytes(c"missing object closure", 22)- )- }- return wire.write_frame(s.s, wire.END, f.request_id, bytes.empty())-}--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 first_target(ts: view.TargetSet) option[objid.Id] = trust {- if @len(ts.adds) > 0 {- return @get(ts.adds, 0)- }- return none-}--fn ref_matches(v: ref view.View, name: bytes.Bytes, expected: bytes.Bytes) bool = trust {- val bm = find_bookmark(v, name)- val tg = find_tag(v, name)- val current: mut option[objid.Id] = none- if bm >= 0 {- val o = @get(v.bookmarks, bm as usize)- if o is some b {- current = first_target(b.targets)- }- } elif tg >= 0 {- val o2 = @get(v.tags, tg as usize)- if o2 is some t {- current = some t.target- }- }- if expected.ptr == none {- if current is none {- return true- }- return false- }- if current is some id {- return objid.Id.eql(id, objid.id(expected.ptr))- }- return false-}--fn apply_ref(v: mut ref view.View, name: bytes.Bytes, target: bytes.Bytes) void = trust {- val bm = find_bookmark(v, name)- if target.ptr == none {- if bm >= 0 {- val o = @get(v.bookmarks, bm as usize)- if o is some b {- @listfree(b.targets.adds)- @listfree(b.targets.removes)- if b.name.ptr != none {- bytes.free_ptr(b.name.ptr)- }- @free(b as ref void)- }- @remove(v.bookmarks, bm as usize)- }- val tg = find_tag(v, name)- if tg >= 0 {- val o2 = @get(v.tags, tg as usize)- if o2 is some t {- if t.name.ptr != none {- bytes.free_ptr(t.name.ptr)- }- @free(t as ref void)- }- @remove(v.tags, tg as usize)- }- return- }- val tid: objid.Id = objid.id(target.ptr)- if bm >= 0 {- val o3 = @get(v.bookmarks, bm as usize)- if o3 is some b3v {- @listfree(b3v.targets.adds)- @listfree(b3v.targets.removes)- b3v.targets = view.empty_target_set()- @append(b3v.targets.adds, copy_id(tid))- }- return- }- val tg2 = find_tag(v, name)- if tg2 >= 0 {- val o4 = @get(v.tags, tg2 as usize)- if o4 is some t2 {- t2.target = copy_id(tid)- }- return- }- val nb: mut ref view.Bookmark = @alloc(@sizeof(view.Bookmark)) as ref view.Bookmark- nb.name = bytes.Bytes.dup(name)- nb.targets = view.empty_target_set()- @append(nb.targets.adds, copy_id(tid))- @append(v.bookmarks, nb)-}--fn handle_update_refs(s: mut ref Session, f: wire.Frame) bool = trust {- if deny(s, f.request_id, true) {- return true- }- if s.quota_bytes > 0 && quota.used(s.quota_dir) + QUOTA_RESERVE >= s.quota_bytes {- return wire.write_error(- s.s,- f.request_id,- wire.ERR_QUOTA,- bytes.bytes(c"storage quota exceeded", 23)- )- }- val dec = msg.decode_update_refs(f.payload)- val updates: mut list[msg.UpdateRef] = lists.new[msg.UpdateRef]()- match dec {- ok v => {- updates = v- }- err _ => {- wire.write_error(- s.s,- f.request_id,- wire.ERR_BAD_FRAME,- bytes.bytes(c"bad UPDATE_REFS", 15)- )- return true- }- }- val tx_opt = txnmod.begin(s.repo)- val tx: mut ref txnmod.Txn = none- match tx_opt {- some t => {- tx = t- }- none => {- msg.free_updates(updates)- wire.write_error(- s.s,- f.request_id,- wire.ERR_INTERNAL,- bytes.bytes(c"cannot update refs", 18)- )- return true- }- }- val conflict: mut bool = false- for u in updates {- if !ref_matches(tx.view, u.name, u.expected) {- conflict = true- break- }- }- if conflict {- txnmod.abort(tx)- msg.free_updates(updates)- return wire.write_error(- s.s,- f.request_id,- wire.ERR_REF_CONFLICT,- bytes.bytes(c"ref changed", 11)- )- }- for u in updates {- apply_ref(tx.view, u.name, u.target)- }- viewops.rebuild_heads(tx.view)- val status: i32 = txnmod.finish(tx, bytes.bytes(c"remote push", 11))- msg.free_updates(updates)- if status != 0 {- return wire.write_error(- s.s,- f.request_id,- wire.ERR_INTERNAL,- bytes.bytes(c"commit failed", 13)- )- }- val fp_text: bytes.Bytes = ed.base32_text(s.fingerprint)- val line: ref u8 = @fmtalloc(- "{d} {s} update-refs\n",- {time.unix_now_millis(), str.view(fp_text.ptr, fp_text.len as i64)}- )- log_line(s, bytes.from_cstr(line))- @free(line as ref void)- bytes.free_owned(fp_text)- return wire.write_simple(s.s, wire.UPDATE_REFS_OK, f.request_id)-}--fn dispatch(s: mut ref Session, f: wire.Frame, root: option[layout.Repo]) bool = trust {- if f.kind == wire.HELLO {- return handle_hello(s, f, root)- }- if f.kind == wire.AUTH {- return handle_auth(s, f)- }- if f.kind == wire.WHOAMI {- return handle_whoami(s, f)- }- if !s.repo_present {- wire.write_error(- s.s,- f.request_id,- wire.ERR_UNAUTHENTICATED,- bytes.bytes(c"authentication required", 23)- )- return true- }- if f.kind == wire.LIST_REFS {- return handle_list_refs(s, f)- }- if f.kind == wire.NEGOTIATE {- return handle_negotiate(s, f)- }- if f.kind == wire.FETCH_SKELETON {- return handle_fetch(s, f)- }- if f.kind == wire.GET_CHUNKS {- return handle_get_chunks(s, f)- }- if f.kind == wire.HAVE_QUERY {- return handle_have_query(s, f)- }- if f.kind == wire.PUT_RECORDS {- return handle_put_records(s, f)- }- if f.kind == wire.UPDATE_REFS {- return handle_update_refs(s, f)- }- return wire.write_error(- s.s,- f.request_id,- wire.ERR_BAD_FRAME,- bytes.bytes(c"unknown request", 15)- )-}--fn free_session(s: mut ref Session) void = trust {- if s.store_open {- store.close_handles(s.handles)- }- if s.repo_present {- access.free(s.access)- layout.free_repo(s.repo)- }- free_bytes_list(s.haves)- files.free_path(s.quota_dir)- if s.hello_repo.ptr != none {- bytes.free_ptr(s.hello_repo.ptr)- }- if s.server_nonce.ptr != none {- bytes.free_ptr(s.server_nonce.ptr)- }- if s.client_nonce.ptr != none {- bytes.free_ptr(s.client_nonce.ptr)- }- if s.binding.ptr != none {- bytes.free_ptr(s.binding.ptr)- }- if s.public_key.ptr != none {- bytes.free_ptr(s.public_key.ptr)- }- if s.fingerprint.ptr != none {- bytes.free_ptr(s.fingerprint.ptr)- }- @free(s as ref void)-}--/// Serve one connection. `root` is set for `-listen`, `fixed` for `-stdio`.-pub fn session(- st: stream.Stream,- fixed: option[layout.Repo],- root: option[layout.Repo],- binding: bytes.Bytes,- quota_bytes: u64-) void = trust {- val s: mut ref Session = @alloc(@sizeof(Session)) as ref Session- s.s = st- s.repo = layout.Repo{root: bytes.empty()}- s.repo_present = false- s.handles = lists.new[ref store.Handle]()- s.store_open = false- s.access = access.empty()- s.hello_repo = bytes.empty()- s.server_nonce = bytes.empty()- s.client_nonce = bytes.empty()- s.binding = bytes.Bytes.dup(binding)- s.version = msg.PROTOCOL_VERSION- s.authed = false- s.role = access.ROLE_ANONYMOUS- s.public_key = bytes.empty()- s.fingerprint = bytes.empty()- s.haves = lists.new[bytes.Bytes]()- s.quota_bytes = quota_bytes- s.quota_dir = str.view(none, 0)- s.failed_auth = 0- s.closing = false- if fixed is some repo {- s.repo = repo- s.repo_present = true- s.quota_dir = files.join(layout.root_view(repo), str.from_cstr(c""))- s.access = access.load(repo)- if s.access.valid {- open_session_store(s)- }- }- for !s.closing {- val f_opt = wire.read_frame(st)- val f: mut wire.Frame = wire.Frame{- kind: 0,- request_id: 0,- payload: bytes.empty(),- base: bytes.empty()- }- match f_opt {- some x => {- f = x- }- none => {- break- }- }- val keep: bool = dispatch(s, f, root)- wire.free_frame(f)- if !keep {- break- }- }- log_outcome(s, bytes.bytes(c"close", 5))- stream.close(st)- free_session(s)-}--pub fn serve_stdio(repo: layout.Repo, quota_bytes: u64) i32 = trust {- val st: stream.Stream = stream.stdio_stream()- session(st, some repo, none, bytes.empty(), quota_bytes)- return 0-}--fn parse_port(addr: bytes.Bytes) option[i32] = trust {- val colon: mut i64 = -1- val i: mut usize = 0- for i < addr.len {- if bytes.Bytes.at(addr, i) == 58 {- colon = i as i64- }- i++- }- if colon < 0 || colon as usize + 1 >= addr.len {- return none- }- val port: mut i32 = 0- val j: mut usize = (colon as usize) + 1- for j < addr.len {- val c: u8 = bytes.Bytes.at(addr, j)- if c < 48 || c > 57 {- return none- }- port = port * 10 + (c - 48) as i32- j++- }- return some port-}--pub fn serve_listen(- addr: bytes.Bytes,- root: layout.Repo,- cert: bytes.Bytes,- key: bytes.Bytes,- quota_bytes: u64-) i32 = trust {- when linux {- val _ = runtime.signal(13, ignore_sigpipe)- }- when darwin {- val _ = runtime.signal(13, ignore_sigpipe)- }- val port_opt = parse_port(addr)- val port: mut i32 = 0- match port_opt {- some p => {- port = p- }- none => {- cmsg.error_prefix()- stdio.eprint("invalid listen address\n", {})- return 1- }- }- val cert_z: ref u8 = bytes.Bytes.to_cstr(cert)- val key_z: ref u8 = bytes.Bytes.to_cstr(key)- val ctx: ref void = tls.server_ctx(cert_z, key_z)- @free(cert_z as ref void)- @free(key_z as ref void)- if ctx == none {- cmsg.error_prefix()- stdio.eprint("cannot load TLS certificate or key\n", {})- return 1- }- val ac: allocators.HeapAllocator = @zeroed- val server = net.TcpServer.listen[allocators.HeapAllocator](ac, port)- if server == none {- cmsg.error_prefix()- stdio.eprint("cannot listen on port {d}\n", {port})- tls.free_ctx(ctx)- return 1- }- cmsg.info_prefix()- stdio.print("listening on {s}\n", {addr})- for {- val fd: i64 = net.TcpServer.accept(server)- if fd < 0 {- break- }- val ssl: ref void = tls.accept(ctx, fd as i32)- if ssl == none {- net.TcpServer.close_client(fd)- continue- }- val binding: ref u8 = @alloc(32) as ref u8- val exported: bool = tls.exporter(ssl, binding, 32)- val st: stream.Stream = stream.tls_stream(fd as i32, ssl)- val bind: mut bytes.Bytes = bytes.empty()- if exported {- bind = bytes.bytes(binding, 32)- }- val no_repo: option[layout.Repo] = none- session(st, no_repo, some root, bind, quota_bytes)- @free(binding as ref void)- }- net.TcpServer.close[allocators.HeapAllocator](ac, server)- tls.free_ctx(ctx)- return 0-}--- a/veins/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/veins/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/veins/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/veins/src/store/layout.sx+++ /dev/null@@ -1,238 +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 resolutions_dir(r: Repo) str.StringView = {- return files.join(root_view(r), ".veins/resolutions")-}--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/veins/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/veins/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/veins/src/store/state.sx+++ /dev/null@@ -1,269 +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 => {- v.owned = body- 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 => {- op.owned = body- 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 {- @listfree(hs)- 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]()- v.owned = bytes.empty()- 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/veins/src/store/store.sx+++ /dev/null@@ -1,445 +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")-val stat = use("../io/stat.sx")--pub type Handle = {- path: mut str.StringView- pack: mut ref pack.Pack- idx: mut ref index.Index- mtime_ns: mut u64-}--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- h.mtime_ns = 0- @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 {- if h.pack != none {- pack.free_pack(h.pack)- }- if h.idx != none {- index.free_index(h.idx)- }- files.free_path(h.path)- val p: mut ref void = h as ref void- trust @free(p)- }- @listfree(handles)-}--/// Load a handle's index on first use, and its pack only when an object body is-/// actually needed. Most commands touch a handful of recent objects, so eagerly-/// decoding every pack makes each invocation cost time proportional to the-/// whole store.-pub fn ensure_index(h: mut ref Handle) bool = trust {- if h.idx != none {- return true- }- if h.path.len <= 6 {- return false- }- val base_view: str.StringView = str.view(h.path.ptr, h.path.len - 6)- val iview: str.StringView = files.with_suffix(base_view, str.from_cstr(c".vidx"))- val idata_opt = files.read_all(iview)- files.free_path(iview)- val idata: mut bytes.Bytes = bytes.empty()- match idata_opt {- some d => {- idata = d- }- none => {- return false- }- }- val decoded = index.decode(idata, bytes.empty())- match decoded {- ok idx => {- val base: str.StringView = files.basename(h.path)- if base.len <= 6 || !pack_name_matches_trailer(- str.view(base.ptr, base.len - 6),- idx.pack_trailer- ) {- index.free_index(idx)- return false- }- h.idx = idx- return true- }- err _ => {- files.free_buffer(idata)- return false- }- }-}--pub fn ensure_pack(h: mut ref Handle) bool = trust {- if h.pack != none {- return true- }- if !ensure_index(h) {- return false- }- val data_opt = files.read_all(h.path)- val data: mut bytes.Bytes = bytes.empty()- match data_opt {- some d => {- data = d- }- none => {- return false- }- }- val decoded = pack.decode(data)- match decoded {- ok p => {- if !bytes.Bytes.eql(p.trailer, h.idx.pack_trailer) {- pack.free_pack(p)- return false- }- h.pack = p- return true- }- err _ => {- files.free_buffer(data)- return false- }- }-}--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 = trust {- val i: mut usize = 0- for i < @len(handles) {- val h: mut ref Handle = handle_list_at(handles, i)- if !ensure_index(h) {- i++- continue- }- val found = index.Index.find(h.idx, id)- if found is some pos {- val off: u64 = index.Index.offset_at(h.idx, pos)- if !ensure_pack(h) {- i++- continue- }- 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] = trust {- 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] = trust {- return lookup_handles(store.handles, id)-}--pub fn handle_list_at(handles: list[ref Handle], i: usize) mut 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] = trust {- pre {- pack_in_bounds: loc.pack_index < @len(handles)- }- val h: mut ref Handle = handle_list_at(handles, loc.pack_index)- if !ensure_pack(h) {- return err derr.fail(derr.ErrorKind.Corrupt, 0)- }- return pack.get(h.pack, loc.record_index)-}--pub fn get(store: Store, loc: Loc) result[bytes.Bytes, derr.DecodeError] = trust {- return get_handles(store.handles, loc)-}--fn pack_name_matches_trailer(name: str.StringView, trailer: bytes.Bytes) bool = trust {- if name.len != 64 || trailer.len != 32 {- return false- }- val hex: ref u8 = @alloc(65) as ref u8- objid.hex_encode(trailer.ptr, 32, hex)- @store8(@ptradd(hex, 64), 0)- val same: bool = bytes.Bytes.eql(bytes.bytes(name.ptr, 64), bytes.from_cstr(hex))- @free(hex as ref void)- return same-}--fn lazy_handle(packs_dir: str.StringView, name: str.StringView) mut ref Handle = trust {- val pview: str.StringView = files.join(packs_dir, name)- val h: mut ref Handle = @alloc(@sizeof(Handle)) as ref Handle- h.path = pview- h.pack = none- h.idx = none- h.mtime_ns = 0- val info = stat.read(pview)- if info is some si {- h.mtime_ns = si.mtime_ns- }- return h-}--fn handle_ref_at(xs: list[ref Handle], i: usize) ref Handle = trust {- val o = @get(xs, i)- if o is some h {- return h- }- assert false- return none-}--fn merge_sort_handles(- xs: mut list[ref Handle],- lo: usize,- hi: usize,- tmp: mut list[ref Handle]-) void = trust {- if hi - lo <= 1 {- return- }- val mid: usize = lo + (hi - lo) / 2- merge_sort_handles(xs, lo, mid, tmp)- merge_sort_handles(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 = handle_ref_at(xs, i).mtime_ns >= handle_ref_at(xs, j).mtime_ns- }- if take_left {- @set(tmp, k, handle_ref_at(xs, i))- i++- } else {- @set(tmp, k, handle_ref_at(xs, j))- j++- }- k++- }- val m: mut usize = lo- for m < hi {- @set(xs, m, handle_ref_at(tmp, m))- m++- }-}--/// Order packs newest first so lookups usually touch only the most recent one.-fn sort_handles(xs: mut list[ref Handle]) void = trust {- val n: usize = @len(xs)- if n <= 1 {- return- }- val tmp: mut list[ref Handle] = lists.new[ref Handle]()- val i: mut usize = 0- for i < n {- @append(tmp, none)- i++- }- merge_sort_handles(xs, 0, n, tmp)- @listfree(tmp)-}--/// Load every valid pack/index pair. Invalid pairs are skipped; `fsck` reports-/// them in detail.-pub fn open_all(repo: layout.Repo) Store = trust {- 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") && nv.len > 6 {- @append(store.handles, lazy_handle(dir, nv))- }- }- files.free_names(names)- files.free_path(dir)- sort_handles(store.handles)- return store-}--fn has_name(handles: list[ref Handle], name: ref u8) bool = trust {- for h in handles {- if files.name_ends_with(h.path.ptr, name) {- return true- }- }- return false-}--/// Add any packs written since the store was opened. Commands that perform-/// several transactions can keep one store instead of rescanning from scratch.-pub fn refresh(store: mut Store, repo: layout.Repo) void = trust {- val dir: str.StringView = layout.packs_dir(repo)- if !files.exists_dir(dir) {- 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".vpack") && nv.len > 6 && !has_name(store.handles, n) {- @append(store.handles, lazy_handle(dir, nv))- }- }- files.free_names(names)- files.free_path(dir)- sort_handles(store.handles)-}--/// 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/veins/src/store/txn.sx+++ /dev/null@@ -1,647 +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- store: mut store.Store- owns_store: mut bool- 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_remote_refs(xs: mut list[ref view.RemoteRef]) void = trust {- val i: mut usize = 1- for i < @len(xs) {- val cur = @get(xs, i)- val c: mut ref view.RemoteRef = 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.RemoteRef = none- if prev_opt is some v2 {- prev = v2- }- val cmp: i64 = bytes.Bytes.cmp(prev.remote, c.remote)- val ordered: bool = cmp < 0 || (cmp == 0 && bytes.Bytes.cmp(prev.name, c.name) <= 0)- if ordered {- break- }- @set(xs, j, prev)- j--- }- @set(xs, j, c)- 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++- }-}--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 st: store.Store = store.open_all(repo)- return begin_owned(repo, st, true)-}--/// Start a transaction on an already open store. The caller keeps ownership of-/// the store and must close it after the transaction finishes.-pub fn begin_with(repo: layout.Repo, st: store.Store) option[ref Txn] = trust {- return begin_owned(repo, st, false)-}--fn begin_owned(repo: layout.Repo, st: store.Store, owns: bool) option[ref Txn] = trust {- val heads: list[objid.Id] = state.heads(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 => {- if owns {- 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 => {- if owns {- 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- }- 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 => {- if owns {- store.close(st)- }- 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.store = st- tx.owns_store = owns- tx.parents = heads- tx.start_ms = time.unix_now_millis()- return some tx-}--/// Handles for the store snapshot the transaction loaded. Valid until the-/// transaction is finished or aborted.-pub fn handles(tx: ref Txn) list[ref store.Handle] = {- return tx.store.handles-}--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)-}--pub fn enable_chunk_cache(tx: mut ref Txn) void = trust {- writer.enable_chunk_cache(tx.writer)-}--pub fn find_cached(tx: ref Txn, kind: u8, id: objid.Id) option[bytes.Bytes] = trust {- return writer.find_cached(tx.writer, kind, id)-}--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)- }- if tx.owns_store {- store.close(tx.store)- }- 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)-}--/// Put view entries back into the canonical order required by the format.-fn prepare_view(v: mut ref view.View) void = trust {- sort_heads(v.heads)- sort_bookmarks(v.bookmarks)- sort_tags(v.tags)- sort_remote_refs(v.remote_refs)- sort_workspaces(v.working_copies)-}--fn encode_canonical_view(v: mut ref view.View) bytes.Bytes = trust {- prepare_view(v)- return view.encode(v)-}--/// 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 = encode_canonical_view(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- op.owned = bytes.empty()- 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) == 0- 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-}--fn test_id(fill: u8) objid.Id = trust {- val p: ref u8 = @alloc(32) as ref u8- val i: mut usize = 0- for i < 32 {- @store8(@ptradd(p, i as i64), fill)- i++- }- return objid.id(p)-}--test "transaction view entries are sorted before encoding" {- trust {- val v: mut ref view.View = state.empty_view()- val low: objid.Id = test_id(17)- val high: objid.Id = test_id(34)- @append(v.heads, copy_id(high))- @append(v.heads, copy_id(low))-- val main_bm: mut ref view.Bookmark = @alloc(@sizeof(view.Bookmark)) as ref view.Bookmark- main_bm.name = bytes.Bytes.dup(bytes.bytes(c"main", 4))- main_bm.targets = view.empty_target_set()- @append(main_bm.targets.adds, copy_id(low))- @append(v.bookmarks, main_bm)-- val feat_bm: mut ref view.Bookmark = @alloc(@sizeof(view.Bookmark)) as ref view.Bookmark- feat_bm.name = bytes.Bytes.dup(bytes.bytes(c"feat", 4))- feat_bm.targets = view.empty_target_set()- @append(feat_bm.targets.adds, copy_id(high))- @append(v.bookmarks, feat_bm)-- val rr_main: mut ref view.RemoteRef = @alloc(@sizeof(view.RemoteRef)) as ref view.RemoteRef- rr_main.remote = bytes.Bytes.dup(bytes.bytes(c"origin", 6))- rr_main.name = bytes.Bytes.dup(bytes.bytes(c"main", 4))- rr_main.target = copy_id(low)- @append(v.remote_refs, rr_main)-- val rr_feat: mut ref view.RemoteRef = @alloc(@sizeof(view.RemoteRef)) as ref view.RemoteRef- rr_feat.remote = bytes.Bytes.dup(bytes.bytes(c"origin", 6))- rr_feat.name = bytes.Bytes.dup(bytes.bytes(c"feat", 4))- rr_feat.target = copy_id(high)- @append(v.remote_refs, rr_feat)-- val body: bytes.Bytes = encode_canonical_view(v)- val decoded = view.decode(body)- match decoded {- ok out => {- assert @len(out.heads) == 2- assert @len(out.bookmarks) == 2- val first = @get(out.bookmarks, 0)- if first is some bm {- assert bytes.Bytes.eql(bm.name, bytes.bytes(c"feat", 4))- } else {- assert false- }- view.free_view(out)- }- err _ => {- assert false- }- }- bytes.free_owned(body)- view.free_view(v)- }-}--- a/veins/src/store/viewops.sx+++ /dev/null@@ -1,296 +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++- }-}--/// Recompute `heads` from the visible roots. Keeping stale heads makes deleted-/// bookmarks remain visible and would export commits that are no longer-/// referenced, so the list is rebuilt from scratch.-pub fn rebuild_heads(v: mut ref view.View) void = trust {- // Head IDs may point into a decoded view body; only the list itself is- // owned by this view, never the individual ID spans.- @listfree(v.heads)- v.heads = lists.new[objid.Id]()- 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)-}--/// Move bookmarks that point at `old_id` to `new_id`.-///-/// This is how a named branch follows a commit that is rewritten by the-/// working-copy snapshotter, `describe`, or `rm`. It is an explicit consequence-/// of the state-changing command that rewrote the commit; `checkout` and `new`-/// do not call it.-pub fn move_bookmarks(v: ref view.View, old_id: objid.Id, new_id: objid.Id) void = trust {- if same(old_id, new_id) {- return- }- val i: mut usize = 0- for i < @len(v.bookmarks) {- val existing = @get(v.bookmarks, i)- if existing is some bm {- if contains(bm.targets.adds, old_id) {- @listfree(bm.targets.adds)- @listfree(bm.targets.removes)- bm.targets.adds = lists.new[objid.Id]()- bm.targets.removes = lists.new[objid.Id]()- @append(bm.targets.adds, copy_id(new_id))- }- }- i++- }-}--pub fn find_bookmark(v: ref view.View, name: bytes.Bytes) option[usize] = 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 some i- }- }- i++- }- return none-}--pub fn set_bookmark(v: ref view.View, name: bytes.Bytes, id: objid.Id) void = trust {- val idx = find_bookmark(v, name)- if idx is some i {- val o = @get(v.bookmarks, i)- if o is some bm {- @listfree(bm.targets.adds)- @listfree(bm.targets.removes)- bm.targets = view.empty_target_set()- @append(bm.targets.adds, copy_id(id))- }- return- }- val bm2: mut ref view.Bookmark = @alloc(@sizeof(view.Bookmark)) as ref view.Bookmark- bm2.name = bytes.Bytes.dup(name)- bm2.targets = view.empty_target_set()- @append(bm2.targets.adds, copy_id(id))- @append(v.bookmarks, bm2)-}--pub 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++- }-}--pub 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++- }-}--/// True when the bookmark's target set is the resolved single target `id`.-pub fn bookmark_points_at(bm: ref view.Bookmark, id: objid.Id) bool = trust {- if @len(bm.targets.adds) != 1 || @len(bm.targets.removes) != 0 {- return false- }- val o = @get(bm.targets.adds, 0)- if o is some only {- return same(only, id)- }- return false-}--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/veins/src/store/writer.sx+++ /dev/null@@ -1,555 +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 CachedObj = {- kind: mut u8- id: mut objid.Id- body: mut bytes.Bytes-}--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- quota_hit: mut bool- limit: mut u64- seen: mut idmap.IdSet- cache: mut list[ref CachedObj]- cache_chunks: mut bool-}--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_cached(items: list[ref CachedObj]) void = trust {- for c in items {- if c.body.ptr != none {- val bp: mut ref void = c.body.ptr as ref void- @free(bp)- }- if c.id.ptr != none {- val ip: mut ref void = c.id.ptr as ref void- @free(ip)- }- val cp: mut ref void = c as ref void- @free(cp)- }- @listfree(items)-}--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 _ => {- }- }- allocators.HeapAllocator.free(ac, t)- }- j++- }- val jf: mut usize = 0- for jf < @len(jobs) {- val jo = @get(jobs, jf)- if jo is some jobp {- @free(jobp as ref void)- }- jf++- }- @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 {- return open_limited(repo, 0)-}--/// Open a pack writer that refuses to write more than `limit` bytes of pack and-/// index data. A zero limit means unlimited.-pub fn open_limited(repo: layout.Repo, limit: u64) 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.quota_hit = false- w.limit = limit- w.seen = idmap.new(1024)- w.cache = lists.new[ref CachedObj]()- w.cache_chunks = false- 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)- // Chunks dominate memory for large snapshots, so they are only retained- // when a command needs to read objects it wrote in the same transaction.- if kind != 1 || w.cache_chunks {- val c: mut ref CachedObj = @alloc(@sizeof(CachedObj)) as ref CachedObj- c.kind = kind- c.id = copy_id(id)- c.body = bytes.Bytes.dup(body)- @append(w.cache, c)- }- 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- val flush_at: mut usize = 268435456- if w.limit > 0 && w.limit < flush_at as u64 {- flush_at = w.limit as usize- }- if w.pending_bytes >= flush_at {- 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)- free_cached(w.cache)- 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- val record_bytes: u64 = header.len as u64 + r.stored.len as u64- if w.limit > 0 && start + record_bytes + 32 > w.limit {- w.quota_hit = true- w.failed = true- break- }- 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-}--pub fn enable_chunk_cache(w: mut Writer) void = trust {- w.cache_chunks = true-}--/// Look up an object written during this writer's lifetime. The returned body-/// is borrowed from the writer.-pub fn find_cached(w: ref Writer, kind: u8, id: objid.Id) option[bytes.Bytes] = trust {- for c in w.cache {- if c.kind == kind && objid.Id.eql(c.id, id) {- return some c.body- }- }- return none-}--/// Finish the pack and write its index. `w` is consumed. Returns 0 on success,-/// 1 on a write failure, and 2 when the configured byte limit was reached.-pub fn finish(w: mut ref Writer) i32 = trust {- if w.failed {- val quota_hit: bool = w.quota_hit- abort(w)- if quota_hit {- return 2- }- return 1- }- if !write_pending(w) {- val quota_hit: bool = w.quota_hit- abort(w)- if quota_hit {- return 2- }- return 1- }-- 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 1- }-- if !native.seek_set(w.fd, 0) {- abort(w)- return 1- }- 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 1- }- 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 1- }-- records.sort_by_id(w.metas)- val index_bytes: bytes.Bytes = index.encode(w.metas, trailer)- if w.limit > 0 && w.offset + 32 + index_bytes.len as u64 > w.limit {- val idx_buf: mut ref void = index_bytes.ptr as ref void- @free(idx_buf)- @free(digest as ref void)- abort(w)- return 2- }-- 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 {- val idx_buf: mut ref void = index_bytes.ptr as ref void- @free(idx_buf)- @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 1- }- val _ = native.sync_dir_path(w.packs_dir)-- 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)- if wrote_index {- return 0- }- return 1-}--- a/veins/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/veins/src/worktree/attr_repro_main.sx+++ /dev/null@@ -1,11 +0,0 @@-val stdio = use("std/stdio")-val str = use("std/string")-val attr = use("attributes.sx")-pub fn main() i32 = trust {- val rules: attr.Rules = attr.load(str.from_cstr(c"/tmp"))- val item = @get(rules.items, 0)- if item is some r {- stdio.print("len={d} ptr={d}\n", {r.pattern.len as u64, r.pattern.ptr as u64})- }- return 0-}--- a/veins/src/worktree/checkout.sx+++ /dev/null@@ -1,1792 +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 fs = use("std/fs")-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 conflict = use("../object/conflict.sx")-val prim = use("../core/primitives.sx")-val identity = use("../core/identity.sx")-val random = use("std/crypto/random")-val repoconfig = use("../core/repoconfig.sx")-val graph = use("../object/graph.sx")-val treewalk = use("../object/treewalk.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 txn = use("../store/txn.sx")-val viewops = use("../store/viewops.sx")-val promisor = use("../protocol/promisor.sx")-val snapshot = use("../worktree/snapshot.sx")-val files = use("../io/files.sx")-val native = use("../io/native.sx")-val stat = use("../io/stat.sx")-val object = use("../git/object.sx")-val lazy = use("../git/lazy.sx")-val filemerge = use("../merge/filemerge.sx")--extern (C) fn openat(dirfd: i32, path: ref u8, flags: 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 ConflictTask = {- path: mut bytes.Bytes- target: mut objid.Id-}--pub type CheckoutWalk = {- handles: list[ref store.Handle]- tasks: mut list[ref CheckoutTask]- dirs: mut list[bytes.Bytes]- conflicts: mut list[ref ConflictTask]- 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 {- 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 free_id(id: objid.Id) void = trust {- if id.ptr != none {- val p: mut ref void = id.ptr as ref void- @free(p)- }-}--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)- val chunk2: mut option[bytes.Bytes] = chunk_opt- if chunk2 is none {- promisor.ensure(handles)- if promisor.is_active() {- chunk2 = promisor.fetch_chunk(e.id)- }- }- match chunk2 {- 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- walk.error = bytes.Bytes.dup(e.name)- 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)- } elif e.kind == tree.KIND_CONFLICT {- val ct: mut ref ConflictTask = @alloc(@sizeof(ConflictTask)) as ref ConflictTask- ct.path = path- ct.target = copy_id(e.target)- @append(walk.conflicts, ct)- } else {- walk.error = bytes.Bytes.dup(path)- files.free_buffer(path)- walk.failed = true- }- }- tree.free_tree(t)- files.free_buffer(body)-}--fn tree_of_commit(- 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(copy_id(lc.c.root_tree))- graph.free_loaded(lc)- }- return out-}--fn prune_empty_parents(repo: layout.Repo, rel: bytes.Bytes) void = trust {- val i: mut usize = rel.len- for i > 0 {- val slash: mut i64 = -1- val k: mut usize = 0- for k < i {- if bytes.Bytes.at(rel, k) == 47 {- slash = k as i64- }- k++- }- if slash < 0 {- break- }- val parent: bytes.Bytes = bytes.Bytes.slice(rel, 0, slash as usize)- val parent_view: str.StringView = str.view(parent.ptr, parent.len as i64)- val abs: str.StringView = files.join(layout.root_view(repo), parent_view)- val removed: bool = fs.rmdir_path(abs)- files.free_path(abs)- if !removed {- break- }- i = slash as usize- }-}--/// Delete files that were tracked by the old tree but are not part of the new-/// tree. Untracked and ignored files are never touched.-fn delete_stale(- repo: layout.Repo,- handles: list[ref store.Handle],- old_tree: option[objid.Id],- new_tree: option[objid.Id]-) bool = trust {- val old_entries: list[ref treewalk.FlatEntry] = treewalk.flatten_or_empty(handles, old_tree)- val new_entries: list[ref treewalk.FlatEntry] = treewalk.flatten_or_empty(handles, new_tree)- val success: mut bool = true- for e in old_entries {- if e.kind == tree.KIND_SUBMODULE {- continue- }- val keep = treewalk.lookup(new_entries, e.path)- if keep is some _ {- continue- }- val rel: str.StringView = str.view(e.path.ptr, e.path.len as i64)- val abs: str.StringView = files.join(layout.root_view(repo), rel)- val info_opt = stat.read(abs)- val existed: mut bool = false- if info_opt is some info {- if info.kind != stat.KIND_MISSING {- existed = true- }- }- if existed {- if !files.delete(abs) {- success = false- } else {- prune_empty_parents(repo, e.path)- }- }- files.free_path(abs)- }- treewalk.free_flat(old_entries)- treewalk.free_flat(new_entries)- return success-}---fn adjacent_config(repo: layout.Repo) bool = trust {- val v = repoconfig.get(repo, bytes.bytes(c"merge.adjacent", 14))- if v is some value {- val on: bool = bytes.Bytes.eql(value, bytes.bytes(c"merge", 5))- files.free_buffer(value)- return on- }- return false-}--fn abs_rel(repo: layout.Repo, path: bytes.Bytes) str.StringView = trust {- return files.join3(layout.root_view(repo), str.from_cstr(c""), files.to_view(path))-}--fn suffix_path(path: bytes.Bytes, suffix: bytes.Bytes) bytes.Bytes = trust {- val out: ref u8 = @alloc(path.len + suffix.len) as ref u8- if path.len > 0 {- @memcpy(out as ref void, path.ptr as ref void, path.len)- }- if suffix.len > 0 {- @memcpy(- @ptradd(out, path.len as i64) as ref void,- suffix.ptr as ref void,- suffix.len- )- }- return bytes.bytes(out, path.len + suffix.len)-}--fn remove_path(repo: layout.Repo, path: bytes.Bytes) void = trust {- val abs: str.StringView = abs_rel(repo, path)- val info_opt = stat.read(abs)- if info_opt is some info {- if info.kind == stat.KIND_DIR {- val names: list[ref u8] = files.list_dir(abs)- for n in names {- val child: bytes.Bytes = suffix_path(path, bytes.bytes(c"/", 1))- val child2: bytes.Bytes = suffix_path(child, bytes.from_cstr(n))- remove_path(repo, child2)- files.free_buffer(child)- files.free_buffer(child2)- }- files.free_names(names)- val _ = fs.rmdir_path(abs)- } else {- val _ = files.delete(abs)- }- }- files.free_path(abs)-}--fn delete_sidecars(repo: layout.Repo, path: bytes.Bytes) void = trust {- val suffixes: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()- @append(suffixes, bytes.bytes(c".base", 5))- @append(suffixes, bytes.bytes(c".ours", 5))- @append(suffixes, bytes.bytes(c".theirs", 7))- val n: mut usize = 2- for n <= 64 {- val b1: ref u8 = @fmtalloc(".base{d}", {n})- @append(suffixes, bytes.from_cstr(b1))- val b2: ref u8 = @fmtalloc(".theirs{d}", {n})- @append(suffixes, bytes.from_cstr(b2))- n++- }- for suffix in suffixes {- val full: bytes.Bytes = suffix_path(path, suffix)- remove_path(repo, full)- files.free_buffer(full)- }- @listfree(suffixes)-}--fn write_bytes_path(- root_fd: i32,- path: bytes.Bytes,- data: bytes.Bytes,- executable: bool-) bool = trust {- val target_opt = open_parent(root_fd, path)- if target_opt is none {- return false- }- val t: mut CheckoutTarget = CheckoutTarget{fd: 0, name: none, owned_fd: false}- if target_opt is some tt {- t = tt- }- val flags: i32 = o_wronly() | o_creat() | o_trunc() | o_nofollow() | o_cloexec()- val mut_fd: mut i32 = openat(t.fd, t.name, flags, FILE_MODE as i32)- if mut_fd < 0 {- val _ = unlinkat(t.fd, t.name, 0)- mut_fd = openat(t.fd, t.name, flags, FILE_MODE as i32)- }- val fd: i32 = mut_fd- val success: mut bool = false- if fd >= 0 {- success = native.write_fd_all(fd, data)- if success {- val want: mut u32 = FILE_MODE- if executable {- want = EXEC_MODE- }- if fchmod(fd, want) != 0 {- success = false- }- }- close(fd)- }- close_target(t)- return success-}--fn write_path_task(- handles: list[ref store.Handle],- root_fd: i32,- git: object.GitRepo,- git_lock: ref void,- has_git: bool,- path: bytes.Bytes,- kind: u8,- target: objid.Id-) bool = trust {- val job: mut ref CheckoutJob = @alloc(@sizeof(CheckoutJob)) as ref CheckoutJob- job.handles = handles- job.root_fd = root_fd- job.tasks = lists.new[ref CheckoutTask]()- job.start = 0- job.step = 1- job.failed = false- job.error = bytes.empty()- job.git = git- job.git_lock = git_lock- job.has_git = has_git- val task: mut ref CheckoutTask = @alloc(@sizeof(CheckoutTask)) as ref CheckoutTask- task.path = bytes.Bytes.dup(path)- task.kind = kind- task.target = copy_id(target)- val success: bool = write_task(job, task)- if !success {- val hx: ref u8 = objid.Id.hex(target)- msg.error_prefix()- stdio.eprint(- "cannot materialize object {s} at {s}\n",- {str.from_cstr(hx), str.view(path.ptr, path.len as i64)}- )- val hp: mut ref void = hx as ref void- @free(hp)- }- files.free_buffer(task.path)- free_id(task.target)- @free(task as ref void)- @listfree(job.tasks)- @free(job as ref void)- return success-}--fn free_walk_lists(walk: CheckoutWalk) void = trust {- for t in walk.tasks {- files.free_buffer(t.path)- free_id(t.target)- val tp: mut ref void = t as ref void- @free(tp)- }- @listfree(walk.tasks)- for d in walk.dirs {- files.free_buffer(d)- }- @listfree(walk.dirs)- for c in walk.conflicts {- files.free_buffer(c.path)- free_id(c.target)- val cp: mut ref void = c as ref void- @free(cp)- }- @listfree(walk.conflicts)-}--fn write_tree_side(- handles: list[ref store.Handle],- root_fd: i32,- git: object.GitRepo,- git_lock: ref void,- has_git: bool,- tree_id: objid.Id,- prefix: bytes.Bytes-) bool = trust {- val walk: mut CheckoutWalk = CheckoutWalk{- handles: handles,- tasks: lists.new[ref CheckoutTask](),- dirs: lists.new[bytes.Bytes](),- conflicts: lists.new[ref ConflictTask](),- failed: false,- error: bytes.empty()- }- walk_tree(walk, tree_id, prefix, 0)- val success: mut bool = !walk.failed- if success && prefix.len > 0 {- if !ensure_dir(root_fd, prefix) {- success = false- }- }- if success {- for d in walk.dirs {- if !ensure_dir(root_fd, d) {- success = false- msg.error_prefix()- stdio.eprint(- "cannot create conflict directory: {s}\n",- {str.view(d.ptr, d.len as i64)}- )- break- }- }- }- if success {- for task in walk.tasks {- if !write_path_task(- handles,- root_fd,- git,- git_lock,- has_git,- task.path,- task.kind,- task.target- ) {- success = false- msg.error_prefix()- stdio.eprint(- "cannot write conflict sidecar: {s}\n",- {str.view(task.path.ptr, task.path.len as i64)}- )- break- }- }- }- free_walk_lists(walk)- return success-}--fn load_conflict(- handles: list[ref store.Handle],- id: objid.Id-) option[ref conflict.Conflict] = trust {- val body_opt = state.read_body(handles, id, types.CONFLICT)- val body: mut bytes.Bytes = bytes.empty()- match body_opt {- some b => {- body = b- }- none => {- return none- }- }- val decoded = conflict.decode(body)- val out: mut option[ref conflict.Conflict] = none- match decoded {- ok c => {- out = some c- }- err _ => {- }- }- if out is none {- files.free_buffer(body)- }- return out-}--fn materialize_value(- repo: layout.Repo,- handles: list[ref store.Handle],- root_fd: i32,- git: object.GitRepo,- git_lock: ref void,- has_git: bool,- path: bytes.Bytes,- v: ref conflict.ConflictValue-) bool = trust {- if v.kind == 0 {- remove_path(repo, path)- return true- }- if v.kind == tree.KIND_SUBTREE {- remove_path(repo, path)- return write_tree_side(handles, root_fd, git, git_lock, has_git, v.target, path)- }- remove_path(repo, path)- return write_path_task(- handles,- root_fd,- git,- git_lock,- has_git,- path,- v.kind,- v.target- )-}--fn materialize_conflict(- repo: layout.Repo,- handles: list[ref store.Handle],- root_fd: i32,- git: object.GitRepo,- git_lock: ref void,- has_git: bool,- path: bytes.Bytes,- target: objid.Id-) bool = trust {- val c_opt = load_conflict(handles, target)- if c_opt is none {- return false- }- val c: mut ref conflict.Conflict = none- if c_opt is some cc {- c = cc- }- val success: mut bool = true- // Base sidecars.- val ri: mut usize = 0- for ri < @len(c.removes) {- val rv = @get(c.removes, ri)- if rv is some value {- val suffix: mut bytes.Bytes = bytes.bytes(c".base", 5)- if ri > 0 {- val s: ref u8 = @fmtalloc(".base{d}", {ri + 1})- suffix = bytes.from_cstr(s)- }- val sp: bytes.Bytes = suffix_path(path, suffix)- if !materialize_value(- repo,- handles,- root_fd,- git,- git_lock,- has_git,- sp,- value- ) {- success = false- }- files.free_buffer(sp)- }- ri++- }- // Add sidecars and the clean merged file.- val ai: mut usize = 0- for ai < @len(c.adds) {- val av = @get(c.adds, ai)- if av is some value {- val suffix: mut bytes.Bytes = bytes.empty()- if ai == 0 {- suffix = bytes.bytes(c".ours", 5)- } elif ai == 1 {- suffix = bytes.bytes(c".theirs", 7)- } else {- val s2: ref u8 = @fmtalloc(".theirs{d}", {ai + 1})- suffix = bytes.from_cstr(s2)- }- val sp2: bytes.Bytes = suffix_path(path, suffix)- if !materialize_value(- repo,- handles,- root_fd,- git,- git_lock,- has_git,- sp2,- value- ) {- success = false- }- files.free_buffer(sp2)- }- ai++- }- // The main path is the merged file with conflicts resolved to ours.- if @len(c.adds) == 0 {- remove_path(repo, path)- } else {- val ours = @get(c.adds, 0)- if ours is some ov {- if ov.kind == 0 {- remove_path(repo, path)- } elif ov.kind == tree.KIND_SUBTREE {- if !write_tree_side(- handles,- root_fd,- git,- git_lock,- has_git,- ov.target,- path- ) {- success = false- }- } else {- val merged_ok: mut bool = false- if @len(c.adds) == 2 && @len(c.removes) == 1 {- val theirs = @get(c.adds, 1)- val base = @get(c.removes, 0)- if theirs is some tv {- if base is some bv {- if tv.kind != 0 && bv.kind != 0- && tv.kind != tree.KIND_SUBTREE- && bv.kind != tree.KIND_SUBTREE {- val git_copy: mut object.GitRepo = git- val merged = filemerge.merge_blobs(- handles,- @addr(git_copy),- has_git,- bv.target,- ov.target,- tv.target,- adjacent_config(repo)- )- if merged is some m {- val exec: bool = ov.kind == tree.KIND_EXECUTABLE- remove_path(repo, path)- merged_ok = write_bytes_path(root_fd, path, m.data, exec)- filemerge.free_edit(m)- }- }- }- }- }- if !merged_ok {- if !write_path_task(- handles,- root_fd,- git,- git_lock,- has_git,- path,- ov.kind,- ov.target- ) {- success = false- }- }- }- }- }- conflict.free_conflict(c)- return success-}--fn free_conflict_tasks(xs: list[ref ConflictTask]) void = trust {- for c in xs {- files.free_buffer(c.path)- free_id(c.target)- val cp: mut ref void = c as ref void- @free(cp)- }- @listfree(xs)-}--fn sidecar_collision(- handles: list[ref store.Handle],- old_tree: option[objid.Id],- conflicts: list[ref ConflictTask]-) option[bytes.Bytes] = trust {- val tracked: list[ref treewalk.FlatEntry] = treewalk.flatten_or_empty(handles, old_tree)- val out: mut option[bytes.Bytes] = none- for ct in conflicts {- val suffixes: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()- @append(suffixes, bytes.bytes(c".base", 5))- @append(suffixes, bytes.bytes(c".ours", 5))- @append(suffixes, bytes.bytes(c".theirs", 7))- val n: mut usize = 2- for n <= 64 {- val b1: ref u8 = @fmtalloc(".base{d}", {n})- @append(suffixes, bytes.from_cstr(b1))- val b2: ref u8 = @fmtalloc(".theirs{d}", {n})- @append(suffixes, bytes.from_cstr(b2))- n++- }- for suffix in suffixes {- val full: bytes.Bytes = suffix_path(ct.path, suffix)- if treewalk.lookup(tracked, full) is some _ {- out = some bytes.Bytes.dup(full)- }- files.free_buffer(full)- if out is some _ {- break- }- }- @listfree(suffixes)- if out is some _ {- break- }- }- treewalk.free_flat(tracked)- return out-}--fn materialize_tree(- repo: layout.Repo,- handles: list[ref store.Handle],- old_tree: option[objid.Id],- new_root: objid.Id-) i32 = trust {- 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", {})- return 1- }-- val tasks: list[ref CheckoutTask] = lists.new[ref CheckoutTask]()- val dirs: list[bytes.Bytes] = lists.new[bytes.Bytes]()- val conflicts: list[ref ConflictTask] = lists.new[ref ConflictTask]()- val walk: mut CheckoutWalk = CheckoutWalk{- handles: handles,- tasks: tasks,- dirs: dirs,- conflicts: conflicts,- failed: false,- error: bytes.empty()- }- walk_tree(walk, new_root, bytes.empty(), 0)- if walk.failed {- msg.error_prefix()- if walk.error.len > 0 {- stdio.eprint(- "checkout tree validation failed at: {s}\n",- {str.view(walk.error.ptr, walk.error.len as i64)}- )- } else {- stdio.eprint("checkout tree validation failed\n", {})- }- close(root_fd)- return 1- }- val collision = sidecar_collision(handles, old_tree, conflicts)- if collision is some cpath {- msg.error_prefix()- stdio.eprint(- "conflict sidecar would overwrite a tracked path: {s}\n",- {str.view(cpath.ptr, cpath.len as i64)}- )- files.free_buffer(cpath)- close(root_fd)- return 1- }- // Remove sidecars from a previous materialization before writing new ones.- val old_flat: list[ref treewalk.FlatEntry] = treewalk.flatten_or_empty(handles, old_tree)- for oe in old_flat {- if oe.kind == tree.KIND_CONFLICT {- delete_sidecars(repo, oe.path)- }- }- treewalk.free_flat(old_flat)-- if !delete_stale(repo, handles, old_tree, some(new_root)) {- msg.error_prefix()- stdio.eprint("cannot remove files that are absent from the target tree\n", {})- close(root_fd)- 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)- 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- }- }- promisor.ensure(handles)- val count: usize = cpu_count()- val n: usize = @len(tasks)- val workers: mut usize = count- if promisor.is_active() {- workers = 1- }- 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 use_threads: bool = !promisor.is_active()- val w: mut usize = 0- for w < workers {- val job: mut ref CheckoutJob = @alloc(@sizeof(CheckoutJob)) as ref CheckoutJob- job.handles = 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)- if use_threads {- 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"))- }- }- } else {- checkout_worker(job as ref void)- }- 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 {- if use_threads {- 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++- }-- for ct in conflicts {- if !materialize_conflict(- repo,- handles,- root_fd,- git_repo,- git_lock,- git_usable,- ct.path,- ct.target- ) {- had_failure = true- if failed_path.len == 0 {- failed_path = bytes.Bytes.dup(ct.path)- }- }- }- free_conflict_tasks(conflicts)- 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", {})- }- return 1- }-- msg.info_prefix()- stdio.print("checked out {d} files\n", {n})- return 0-}--/// Drop the stat cache after files were written or removed by something other-/// than the snapshotter, so the next snapshot re-reads them instead of trusting-/// stale size/mtime/inode data.-pub fn clear_stat_cache(repo: layout.Repo) void = trust {- val dir: str.StringView = layout.working_copy_dir(repo)- val path: str.StringView = files.join(dir, str.from_cstr(c"stat-cache"))- val _ = files.delete(path)- files.free_path(path)- files.free_path(dir)-}--/// Materialize `new_root` into the working tree while removing files tracked by-/// `old_tree`. Used by `vn new <rev>` after it has already created its commit.-pub fn materialize_commit(- repo: layout.Repo,- handles: list[ref store.Handle],- old_tree: option[objid.Id],- new_root: objid.Id-) i32 = trust {- val same: mut bool = false- if old_tree is some old_id {- if objid.Id.eql(old_id, new_root) {- same = true- }- }- if same {- return 0- }- val status: i32 = materialize_tree(repo, handles, old_tree, new_root)- if status == 0 {- clear_stat_cache(repo)- }- return status-}--/// Bring the files in the working directory in line with a view whose-/// working-copy commit may have been removed (`vn op restore`/`vn undo`).-pub fn materialize_optional(- repo: layout.Repo,- handles: list[ref store.Handle],- old_tree: option[objid.Id],- new_tree: option[objid.Id]-) i32 = trust {- if new_tree is some new_root {- return materialize_commit(repo, handles, old_tree, new_root)- }- if !delete_stale(repo, handles, old_tree, none) {- msg.error_prefix()- stdio.eprint("cannot remove files absent from the restored view\n", {})- return 1- }- clear_stat_cache(repo)- return 0-}--/// Check out `rev` (empty means the working-copy commit) into the repository.-/// The working-copy commit is moved to the target, so subsequent edits amend-/// that commit and any bookmark naming it follows the rewrite.-pub fn create_working_copy_commit(- tx: mut ref txn.Txn,- repo: layout.Repo,- parent: objid.Id-) option[objid.Id] = trust {- val lc_opt = graph.load_commit(txn.handles(tx), parent)- val lc: mut ref graph.LoadedCommit = none- match lc_opt {- some v => {- lc = v- }- none => {- return none- }- }- val root: objid.Id = copy_id(lc.c.root_tree)- graph.free_loaded(lc)- val cid: ref u8 = @alloc(16) as ref u8- random.random_bytes(cid as ref void, 16)- val sig = identity.signature(repo)- val parents: mut list[objid.Id] = lists.new[objid.Id]()- @append(parents, parent)- 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- 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)- @listfree(parents)- @listfree(renames)- @listfree(extra)- @free(nc as ref void)- @free(cid as ref void)- identity.free_sig(sig)- free_id(root)- return some new_id-}--pub fn run(repo: layout.Repo, rev: bytes.Bytes) i32 = trust {- val snap: i32 = snapshot.run(repo)- if snap != 0 {- return snap- }- 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 = graph.resolve(store_handle.handles, v, rev)- val target: mut objid.Id = objid.id_none()- val have_target: mut bool = false- if target_opt is some id {- target = copy_id(id)- have_target = true- }- if !have_target {- 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 new_root_opt = tree_of_commit(store_handle.handles, target)- val new_root: mut objid.Id = objid.id_none()- val have_root: mut bool = false- if new_root_opt is some nr {- new_root = nr- have_root = true- }- if !have_root {- msg.error_prefix()- stdio.eprint("cannot read commit\n", {})- view.free_view(v)- store.close(store_handle)- free_id(target)- return 1- }-- val wc_opt = viewops.working_copy(v)- val wc: mut objid.Id = objid.id_none()- val have_wc: mut bool = false- val old_root: mut option[objid.Id] = none- val bookmark_checkout: mut bool = false- val detach_bookmark: mut bool = false- if rev.len > 0 && !bytes.Bytes.eql(rev, bytes.bytes(c"@", 1)) {- if viewops.find_bookmark(v, rev) is some _ {- bookmark_checkout = true- } else {- detach_bookmark = true- }- }- if wc_opt is some id2 {- wc = id2- have_wc = true- old_root = tree_of_commit(store_handle.handles, wc)- }- view.free_view(v)-- val status: mut i32 = materialize_commit(repo, store_handle.handles, old_root, new_root)- if status != 0 {- store.close(store_handle)- free_id(target)- free_id(new_root)- if have_wc {- free_id(wc)- }- if old_root is some or1 {- free_id(or1)- }- return status- }-- val same_target: mut bool = false- if have_wc {- if objid.Id.eql(wc, target) {- same_target = true- } else {- val wc_loaded = graph.load_commit(store_handle.handles, wc)- if wc_loaded is some wl {- if @len(wl.c.parents) == 1 {- val parent0 = @get(wl.c.parents, 0)- if parent0 is some p0 {- if objid.Id.eql(p0, target)- && objid.Id.eql(wl.c.root_tree, new_root)- && wl.c.message.len == 0 {- same_target = true- }- }- }- graph.free_loaded(wl)- }- }- }- if !same_target {- 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", {})- store.close(store_handle)- free_id(target)- free_id(new_root)- if have_wc {- free_id(wc)- }- if old_root is some or2 {- free_id(or2)- }- return 1- }- }- if have_wc {- viewops.remove_head(tx.view, wc)- }- val child_opt = create_working_copy_commit(tx, repo, target)- val child: mut objid.Id = objid.id_none()- val have_child: mut bool = false- if child_opt is some cid {- child = cid- have_child = true- }- if !have_child {- txn.abort(tx)- store.close(store_handle)- free_id(target)- free_id(new_root)- if have_wc {- free_id(wc)- }- if old_root is some or3 {- free_id(or3)- }- return 1- }- viewops.set_workspace(tx.view, child)- viewops.rebuild_heads(tx.view)- val op_status: i32 = txn.finish(tx, bytes.bytes(c"checkout", 8))- if op_status != 0 {- status = op_status- }- free_id(child)- }-- store.close(store_handle)- if status == 0 {- if bookmark_checkout {- val _ = repoconfig.set_current_bookmark(repo, rev)- } elif detach_bookmark {- val _ = repoconfig.clear_current_bookmark(repo)- }- }- free_id(target)- free_id(new_root)- if have_wc {- free_id(wc)- }- if old_root is some or3 {- free_id(or3)- }- return status-}--/// Materialize the working-copy commit without snapshotting first. Used after-/// a clone, when the directory is empty and must not become a new commit.-pub fn materialize_working_copy(repo: layout.Repo) i32 = trust {- 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)- return 1- }- }- val wc_opt = viewops.working_copy(v)- view.free_view(v)- val wc: mut objid.Id = objid.id_none()- match wc_opt {- some id => {- wc = id- }- none => {- store.close(st)- return 1- }- }- val root_opt = tree_of_commit(st.handles, wc)- val root: mut objid.Id = objid.id_none()- match root_opt {- some r => {- root = r- }- none => {- store.close(st)- free_id(wc)- return 1- }- }- val old_none: option[objid.Id] = none- val status: i32 = materialize_commit(repo, st.handles, old_none, root)- store.close(st)- free_id(wc)- free_id(root)- return status-}--- a/veins/src/worktree/ignore.sx+++ /dev/null@@ -1,349 +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)-}--/// Match a single gitignore-style glob against a relative path.-pub fn glob_match(pattern: bytes.Bytes, path: bytes.Bytes) bool = trust {- return glob_here(pattern, 0, path, 0)-}--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-}--/// Evaluate the complete ignore state for one repository-relative path,-/// including root and per-directory `.vnexclude` / `.gitignore` files.-pub fn path_ignored(repo_root: str.StringView, path: bytes.Bytes) bool = trust {- val rules: mut Rules = empty()- load_root(rules, repo_root)-- // Load the rules in every directory that contains the path.- val i: mut usize = 0- for i < path.len {- if bytes.Bytes.at(path, i) == 47 {- val base: bytes.Bytes = bytes.Bytes.slice(path, 0, i)- load_file(rules, repo_root, base, str.from_cstr(c".vnexclude"))- load_file(rules, repo_root, base, str.from_cstr(c".gitignore"))- }- i++- }-- // An ignored ancestor directory keeps its contents out of snapshots.- val result: mut bool = false- val j: mut usize = 0- for j < path.len {- if bytes.Bytes.at(path, j) == 47 {- val dir: bytes.Bytes = bytes.Bytes.slice(path, 0, j)- if ignored(rules, dir, true) {- result = true- break- }- }- j++- }- if !result {- result = ignored(rules, path, false)- }- free(rules)- return result-}--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/veins/src/worktree/pathspec.sx+++ /dev/null@@ -1,152 +0,0 @@-/// Convert command-line path arguments into repository-relative paths.-///-/// Paths are resolved against the current working directory so that-/// `vn rm *.dSYM` in a subdirectory only considers that directory. Glob-/// metacharacters are preserved for callers that expand patterns themselves.--val str = use("std/string")-val fs = use("std/fs")-val path = use("std/path")-val bytes = use("../core/bytes.sx")-val lists = use("../core/lists.sx")-val buf = use("../core/buf.sx")-val files = use("../io/files.sx")--/// Return the current directory relative to `root`, or none when the current-/// directory is outside the repository.-pub fn cwd_relative(root: bytes.Bytes) option[bytes.Bytes] = trust {- val cwd_opt = fs.cwd_cstr()- val cwd: mut ref u8 = none- match cwd_opt {- some c => {- cwd = c- }- none => {- return none- }- }- val canon: ref u8 = path.canonicalize_path(str.from_cstr(cwd))- @free(cwd as ref void)- if canon == none || @strlen(canon) == 0 {- if canon != none {- @free(canon as ref void)- }- return none- }- val cb: bytes.Bytes = bytes.from_cstr(canon)- val result: mut option[bytes.Bytes] = none- if bytes.Bytes.eql(cb, root) {- result = some(bytes.empty())- } elif cb.len > root.len && bytes.Bytes.starts_with(cb, root)- && bytes.Bytes.at(cb, root.len) == 47 {- result = some(bytes.Bytes.dup(bytes.Bytes.slice(cb, root.len + 1, cb.len)))- }- @free(canon as ref void)- return result-}--/// Collapse `.` and `..` components and remove repeated separators.-fn normalize_components(input: bytes.Bytes) option[bytes.Bytes] = trust {- val comps: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()- val i: mut usize = 0- val start: mut usize = 0- for i <= input.len {- val at_end: bool = i == input.len- if at_end || bytes.Bytes.at(input, i) == 47 {- val comp: bytes.Bytes = bytes.Bytes.slice(input, start, i)- if comp.len > 0 && !bytes.Bytes.eql(comp, bytes.bytes(c".", 1)) {- if bytes.Bytes.eql(comp, bytes.bytes(c"..", 2)) {- if @len(comps) == 0 {- @listfree(comps)- return none- }- val _ = @remove(comps, @len(comps) - 1)- } else {- @append(comps, comp)- }- }- start = i + 1- }- i++- }- if @len(comps) == 0 {- @listfree(comps)- return some(bytes.empty())- }- val b: mut buf.Buf = buf.new(64)- val k: mut usize = 0- for k < @len(comps) {- if k > 0 {- buf.Buf.put_u8(b, 47)- }- val o = @get(comps, k)- if o is some comp {- buf.Buf.put_bytes(b, comp)- }- k++- }- val out: bytes.Bytes = bytes.Bytes.dup(buf.Buf.view(b))- buf.Buf.free(b)- @listfree(comps)- return some(out)-}--/// Normalize one operand. Relative operands are joined to `cwd_rel`; absolute-/// operands must live inside `root`. The returned path is repository-relative-/// and owned by the caller.-pub fn normalize(- root: bytes.Bytes,- cwd_rel: bytes.Bytes,- arg: bytes.Bytes-) option[bytes.Bytes] = trust {- if arg.len == 0 {- return none- }- val absolute: bool = bytes.Bytes.at(arg, 0) == 47- if absolute {- val norm_opt = normalize_components(arg)- val norm: mut bytes.Bytes = bytes.empty()- match norm_opt {- some n => {- norm = n- }- none => {- return none- }- }- val root_view: mut bytes.Bytes = root- if root.len > 0 && bytes.Bytes.at(root, 0) == 47 {- root_view = bytes.Bytes.slice(root, 1, root.len)- }- val result: mut option[bytes.Bytes] = none- if norm.len > root_view.len && bytes.Bytes.starts_with(norm, root_view)- && bytes.Bytes.at(norm, root_view.len) == 47 {- result = some(bytes.Bytes.dup(bytes.Bytes.slice(norm, root_view.len + 1, norm.len)))- }- if norm.ptr != none {- val np: mut ref void = norm.ptr as ref void- @free(np)- }- return result- }- val base_view: str.StringView = files.to_view(cwd_rel)- val arg_view: str.StringView = files.to_view(arg)- val joined: str.StringView = files.join(base_view, arg_view)- val joined_bytes: bytes.Bytes = bytes.bytes(joined.ptr, joined.len as usize)- val norm_opt = normalize_components(joined_bytes)- files.free_path(joined)- return norm_opt-}--/// True when an argument contains a wildcard supported by the ignore engine.-pub fn has_glob(v: bytes.Bytes) bool = trust {- val i: mut usize = 0- for i < v.len {- val c: u8 = bytes.Bytes.at(v, i)- if c == 42 || c == 63 {- return true- }- i++- }- return false-}--- a/veins/src/worktree/snapshot.sx+++ /dev/null@@ -1,1169 +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 graph = use("../object/graph.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 renamemod = use("../merge/rename.sx")-val object = use("../git/object.sx")-val repoconfig = use("../core/repoconfig.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(@ptradd(data.ptr, 4), data.len - 4)- 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 ends_with(name: bytes.Bytes, suffix: bytes.Bytes) bool = trust {- if name.len < suffix.len {- return false- }- return bytes.Bytes.eql(- bytes.Bytes.slice(name, name.len - suffix.len, name.len),- suffix- )-}--fn trailing_digits(name: bytes.Bytes) usize = trust {- val i: mut usize = name.len- for i > 0 {- val c: u8 = bytes.Bytes.at(name, i - 1)- if c < 48 || c > 57 {- break- }- i--- }- return name.len - i-}--fn sidecar_base(name: bytes.Bytes) option[bytes.Bytes] = trust {- if ends_with(name, bytes.bytes(c".base", 5)) && name.len > 5 {- return some bytes.Bytes.slice(name, 0, name.len - 5)- }- if ends_with(name, bytes.bytes(c".ours", 5)) && name.len > 5 {- return some bytes.Bytes.slice(name, 0, name.len - 5)- }- if ends_with(name, bytes.bytes(c".theirs", 7)) && name.len > 7 {- return some bytes.Bytes.slice(name, 0, name.len - 7)- }- val digits: usize = trailing_digits(name)- if digits > 0 {- val stem_end: usize = name.len - digits- if stem_end > 5 && ends_with(- bytes.Bytes.slice(name, 0, stem_end),- bytes.bytes(c".base", 5)- ) {- return some bytes.Bytes.slice(name, 0, stem_end - 5)- }- if stem_end > 7- && ends_with(bytes.Bytes.slice(name, 0, stem_end), bytes.bytes(c".theirs", 7)) {- return some bytes.Bytes.slice(name, 0, stem_end - 7)- }- }- return none-}--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- }- if have_old {- val base_opt = sidecar_base(name)- if base_opt is some base_name {- val bidx: i32 = treewalk.find_name(old, base_name)- if bidx >= 0 {- val be = @get(old.entries, bidx as usize)- if be is some bee {- if bee.kind == tree.KIND_CONFLICT {- 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 old_idx >= 0 {- val oe = @get(old.entries, old_idx as usize)- if oe is some olde {- if olde.kind == tree.KIND_CONFLICT {- @append(- entries,- tree.entry(- bytes.Bytes.dup(name),- tree.KIND_CONFLICT,- copy_id(olde.target)- )- )- files.free_buffer(path)- continue- }- }- }- 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)-}--fn similar_pct(repo: layout.Repo) i32 = trust {- val v = repoconfig.get(repo, bytes.bytes(c"rename.autodetect", 17))- if v is some value {- val off: bool = bytes.Bytes.eql(value, bytes.bytes(c"off", 3))- files.free_buffer(value)- if off {- return 0- }- return 60- }- return 60-}--/// Snapshot the working tree into `@`. Returns 0 on success.-pub fn run(repo: layout.Repo) i32 = trust {- val st: mut store.Store = store.open_all(repo)- val status: i32 = run_with(repo, st)- store.close(st)- return status-}--/// Snapshot using an existing store. The store is refreshed with any pack the-/// snapshot wrote and remains owned by the caller.-pub fn run_with(repo: layout.Repo, st: mut store.Store) i32 = trust {- val tx_opt = txn.begin_with(repo, st)- 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 handles: list[ref store.Handle] = txn.handles(tx)- 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(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", {})- 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", {})- 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,- 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 {- 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 {- 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 old_empty: mut bool = false- if c != none {- if @len(c.parents) == 1 {- val p0 = @get(c.parents, 0)- if p0 is some pid {- val parent_opt = graph.load_commit(handles, pid)- if parent_opt is some parent {- old_empty = objid.Id.eql(c.root_tree, parent.c.root_tree)- graph.free_loaded(parent)- }- }- }- }- 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 {- if !old_empty {- 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: mut list[ref commit.Rename] = lists.new[ref commit.Rename]()- if c != none {- for r in c.renames {- @append(- renames,- commit.new_rename(- r.parent_index,- r.kind,- bytes.Bytes.dup(r.from_path),- bytes.Bytes.dup(r.to_path)- )- )- }- }- if old_tree is some old_for_rename {- if !objid.Id.eql(old_for_rename, new_root) {- val gitfake: mut object.GitRepo = @zeroed- val detected = renamemod.detect_tx(- handles,- @addr(gitfake),- false,- some old_for_rename,- some new_root,- similar_pct(repo),- 0,- tx- )- for r in detected {- @append(renames, r)- }- @listfree(detected)- }- }- renamemod.sort_renames(renames)- 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)- for r in nc.renames {- 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(nc.renames)- @listfree(nc.extra)- @free(nc as ref void)-- if have_wc {- remove_wc_head(tx.view, wc)- // A bookmark that named the amended commit follows it.- viewops.move_bookmarks(tx.view, wc, new_commit)- }- val current = repoconfig.current_bookmark(repo)- if current is some name {- if viewops.find_bookmark(tx.view, name) is some _ {- viewops.set_bookmark(tx.view, name, new_commit)- }- bytes.free_owned(name)- }- 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 {- store.refresh(st, repo)- val _ = gitmap.mark_native(repo, new_commit)- }- 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/veins/src/worktree/treeedit.sx+++ /dev/null@@ -1,151 +0,0 @@-/// Small helper for replacing or deleting one path in a tree.--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 treewalk = use("../object/treewalk.sx")-val store = use("../store/store.sx")-val txnmod = use("../store/txn.sx")--fn split(path: bytes.Bytes) usize = trust {- val i: mut usize = 0- for i < path.len && bytes.Bytes.at(path, i) != 47 {- i++- }- return i-}--fn empty_tree(tx: mut ref txnmod.Txn) objid.Id = trust {- val entries: list[ref tree.TreeEntry] = lists.new[ref tree.TreeEntry]()- val encoded = tree.encode(entries)- val body: mut bytes.Bytes = bytes.empty()- match encoded {- ok b => {- body = b- }- err _ => {- return objid.id(none)- }- }- val id: objid.Id = txnmod.add_object(tx, types.TREE, body)- @listfree(entries)- return id-}--fn tree_is_empty(- handles: list[ref store.Handle],- id: objid.Id,- tx: ref txnmod.Txn-) bool = trust {- val t_opt = treewalk.read_tree_tx(handles, id, tx)- if t_opt is some t {- val empty: bool = @len(t.entries) == 0- tree.free_tree(t)- return empty- }- return true-}--fn edit_into(- tx: mut ref txnmod.Txn,- handles: list[ref store.Handle],- tree_id: objid.Id,- path: bytes.Bytes,- present: bool,- kind: u8,- target: objid.Id-) objid.Id = trust {- val t_opt = treewalk.read_tree(handles, tree_id)- if t_opt is none {- return objid.id(none)- }- val t: mut ref tree.Tree = none- if t_opt is some tt {- t = tt- }- val cut: usize = split(path)- val name: bytes.Bytes = bytes.Bytes.slice(path, 0, cut)- val out: mut list[ref tree.TreeEntry] = lists.new[ref tree.TreeEntry]()- val found: mut bool = false- for e in t.entries {- if bytes.Bytes.eql(e.name, name) {- found = true- if cut == path.len {- if present {- @append(out, tree.entry(e.name, kind, target))- }- } elif e.kind == tree.KIND_SUBTREE {- val rest: bytes.Bytes = bytes.Bytes.slice(path, cut + 1, path.len)- val child: objid.Id = edit_into(- tx,- handles,- e.target,- rest,- present,- kind,- target- )- if !objid.Id.is_none(child) && !tree_is_empty(handles, child, tx) {- @append(out, tree.entry(e.name, tree.KIND_SUBTREE, child))- }- } else {- @append(out, tree.entry(e.name, e.kind, e.target))- }- } else {- @append(out, tree.entry(e.name, e.kind, e.target))- }- }- if !found && cut == path.len && present {- @append(out, tree.entry(bytes.Bytes.dup(name), kind, target))- }- val encoded = tree.encode(out)- val body: mut bytes.Bytes = bytes.empty()- match encoded {- ok b => {- body = b- }- err _ => {- for e in out {- val ep: mut ref void = e as ref void- @free(ep)- }- @listfree(out)- tree.free_tree(t)- return objid.id(none)- }- }- val id: objid.Id = txnmod.add_object(tx, types.TREE, body)- for e in out {- val ep: mut ref void = e as ref void- @free(ep)- }- @listfree(out)- tree.free_tree(t)- return id-}---/// Replace one entry. The returned ID is a new tree object.-pub fn replace(- tx: mut ref txnmod.Txn,- handles: list[ref store.Handle],- root: objid.Id,- path: bytes.Bytes,- present: bool,- kind: u8,- target: objid.Id-) option[objid.Id] = trust {- val id: objid.Id = edit_into(tx, handles, root, path, present, kind, target)- if objid.Id.is_none(id) {- return none- }- if tree_is_empty(handles, id, tx) {- val empty: objid.Id = empty_tree(tx)- val ip: mut ref void = id.ptr as ref void- @free(ip)- return some empty- }- return some id-}--- a/veins/sx.lock+++ /dev/null@@ -1,1 +0,0 @@-version "1"--- a/veins/sx.mod+++ /dev/null@@ -1,29 +0,0 @@-entry "./src/main.sx"-version "v0.0.1"-spectre_version "v0.0.18"--var {- NATIVE_ARCH=auto- darwin.aarch64 { NATIVE_ARCH=aarch64 }- darwin.x86_64 { NATIVE_ARCH=x86_64 }- linux.aarch64 { NATIVE_ARCH=aarch64 }- linux.x86_64 { NATIVE_ARCH=x86_64 }-}--build release {- action "./build-native.sh $OUT $NATIVE_ARCH && spectre ./src/main.sx"- flags "-release -link-obj:$OUT/veins_native.o"- output "./vn"- windows {- output "vn.exe"- }-}--build dev {- action "./build-native.sh $OUT $NATIVE_ARCH && spectre ./src/main.sx"- flags "-link-obj:$OUT/veins_native.o"- output "./vn-dev"- windows {- output "vn-dev.exe"- }-}