navid/veins / commit

3fcc3c75bd9f

Navid M <navidmomtahen@gmail.com> · 2026-11-29

parents: 0f6753858315

Browse files at this commit · Download source

all: enhancements to rs implementation
--- a/veinsrs/src/cli/commands/selftest.rs+++ b/veinsrs/src/cli/commands/selftest.rs@@ -41,7 +41,10 @@         build.root.to_hex() == "937fe1a8d674aa28cb9fa074a76ea84cdc1d6c61e209f47bbdebbe4361b698cf",         "manifest blob id",     )?;-    let manifest = blob::decode(&build.objects.last().unwrap().body)?;+    let Some(manifest_object) = build.objects.last() else {+        return expect(false, "manifest object present").map(|()| 0);+    };+    let manifest = blob::decode(&manifest_object.body)?;     expect(manifest.form == BlobForm::Leaf, "manifest form")?;      let empty_tree_body = vec![0u8];--- a/veinsrs/src/cli/history.rs+++ b/veinsrs/src/cli/history.rs@@ -34,6 +34,7 @@     message: String,     author: String,     conflicted: bool,+    has_changes: bool, }  pub fn log(arguments: &[String]) -> Result<u8> {@@ -130,6 +131,11 @@             continue;         };         let message = first_line(&commit.message);+        let has_changes = if working_copy == Some(id) {+            graph::has_changes(&mut store, &commit)?+        } else {+            false+        };         records.push(LogRecord {             id,             root_tree: commit.root_tree,@@ -139,6 +145,7 @@             message,             author: String::from_utf8_lossy(&commit.author.name).into_owned(),             conflicted: false,+            has_changes,         });         for parent in commit.parents {             if seen.insert(parent) {@@ -193,36 +200,47 @@         change_ids[position] = graph::short_change_id(&change_ids, position);     } +    let color = output::enabled();     let mut rendered = String::new();     if titles {-        rendered.push(' ');+        rendered.push_str(&cell("", 1, &[], color));         rendered.push(' ');-        rendered.push_str(&format!("{:<12}", "Commit"));+        rendered.push_str(&cell("Commit", 12, &[], color));         rendered.push_str("  ");-        rendered.push_str(&format!("{:<change_width$}", "Change"));+        rendered.push_str(&cell("Change", change_width, &[], color));         rendered.push_str("  ");-        rendered.push_str(&format!("{:<19}", "Date"));+        rendered.push_str(&cell("Date", 19, &[], color));         rendered.push_str("  ");-        rendered.push_str(&format!("{:<author_width$}", "Author"));+        rendered.push_str(&cell("Author", author_width, &[], color));         rendered.push_str("  Message\n");     }     for (position, record) in records.iter().enumerate() {         let is_working = working_copy == Some(record.id);         let marker = if is_working { "@" } else { " " };-        rendered.push_str(marker);+        let marker_codes: &[&str] = if is_working {+            if record.has_changes { &["96"] } else { &["31"] }+        } else {+            &[]+        };+        rendered.push_str(&cell(marker, 1, marker_codes, color));         rendered.push(' ');-        rendered.push_str(&format!("{:<12}", record.id.short()));+        rendered.push_str(&cell(&record.id.short(), 12, &["31"], color));         rendered.push_str("  ");-        rendered.push_str(&format!("{:<change_width$}", change_ids[position]));+        rendered.push_str(&cell(&change_ids[position], change_width, &["31"], color));         rendered.push_str("  ");-        rendered.push_str(&format!("{:<19}", crate::time::format_utc(record.seconds)));+        rendered.push_str(&cell(+            &crate::time::format_utc(record.seconds),+            19,+            &["2", "36"],+            color,+        ));         rendered.push_str("  ");-        rendered.push_str(&format!("{:<author_width$}", record.author));+        rendered.push_str(&cell(&record.author, author_width, &["36"], color));         rendered.push_str("  ");         if record.message.is_empty() {-            rendered.push_str("<unset>");+            rendered.push_str(&paint("<unset>", &["90"], color));         } else {-            rendered.push_str(&record.message);+            rendered.push_str(&paint(&record.message, &["32"], color));         }         for name in ops::bookmark_names(&view, record.id) {             rendered.push_str(&format!(" [{}]", String::from_utf8_lossy(&name)));@@ -240,6 +258,30 @@     }     output::pager_output(&root, &rendered, pager);     Ok(0)+}++fn paint(text: &str, codes: &[&str], color: bool) -> String {+    if !color || codes.is_empty() {+        return text.to_string();+    }+    let mut out = String::new();+    for code in codes {+        out.push_str("\x1b[");+        out.push_str(code);+        out.push('m');+    }+    out.push_str(text);+    out.push_str("\x1b[0m");+    out+}++/// Colours a cell and pads it to `width` using visible (uncoloured) length.+fn cell(text: &str, width: usize, codes: &[&str], color: bool) -> String {+    let mut out = paint(text, codes, color);+    for _ in text.chars().count()..width {+        out.push(' ');+    }+    out }  fn first_line(message: &[u8]) -> String {--- a/veinsrs/src/cli/worktree_cmd.rs+++ b/veinsrs/src/cli/worktree_cmd.rs@@ -376,8 +376,9 @@     if paths.is_empty() {         paths.push(".".to_string());     }-    let root =-        layout::discover(Path::new(".")).unwrap_or_else(|_| std::env::current_dir().unwrap());+    let root = layout::discover(Path::new("."))+        .or_else(|_| std::env::current_dir())+        .map_err(|_| Error::new("cannot determine the current directory"))?;     if !core::run_editor(&root, &paths, None) {         return Err(Error::new("editor exited with an error"));     }@@ -612,8 +613,10 @@             }             lines[index].attrs = attrs;         } else {-            if lines.last().is_some_and(|line| line.eol.is_empty()) {-                lines.last_mut().unwrap().eol = "\n".to_string();+            if let Some(last) = lines.last_mut() {+                if last.eol.is_empty() {+                    last.eol = "\n".to_string();+                }             }             lines.push(Line {                 text: String::new(),--- a/veinsrs/src/core.rs+++ b/veinsrs/src/core.rs@@ -2,11 +2,10 @@ use std::env; use std::fs; use std::io::{Read, Write};-use std::os::unix::ffi::{OsStrExt, OsStringExt};-use std::os::unix::fs::MetadataExt; use std::path::{Path, PathBuf};  use crate::error::{Error, Result};+use crate::platform;  pub fn is_flag(argument: &str) -> bool {     !argument.is_empty() && argument.starts_with('-')@@ -31,15 +30,15 @@ }  pub fn path_from_bytes(bytes: &[u8]) -> PathBuf {-    PathBuf::from(std::ffi::OsString::from_vec(bytes.to_vec()))+    platform::path_from_bytes(bytes) }  pub fn path_to_bytes(path: &Path) -> Vec<u8> {-    path.as_os_str().as_bytes().to_vec()+    platform::path_to_bytes(path) }  pub fn path_display(path: &Path) -> String {-    String::from_utf8_lossy(path.as_os_str().as_bytes()).into_owned()+    platform::path_display(path) }  pub fn read_file_opt(path: &Path, maximum: u64) -> Option<Vec<u8>> {@@ -107,20 +106,11 @@ }  fn sync_file(path: &Path) -> bool {-    use std::os::unix::io::AsRawFd;-    let Ok(file) = fs::File::open(path) else {-        return false;-    };-    unsafe { libc::fsync(file.as_raw_fd()) == 0 }+    platform::sync_file(path).is_ok() }  fn sync_directory(path: &Path) {-    use std::os::unix::io::AsRawFd;-    if let Ok(directory) = fs::File::open(path) {-        unsafe {-            libc::fsync(directory.as_raw_fd());-        }-    }+    platform::sync_directory(path); }  pub fn write_atomic(tmp_path: &Path, final_path: &Path, data: &[u8]) -> bool {@@ -181,7 +171,7 @@         return names;     };     for entry in entries.flatten() {-        names.push(entry.file_name().into_vec());+        names.push(platform::os_string_to_bytes(entry.file_name()));     }     names }@@ -205,7 +195,7 @@ pub fn path_read_symlink(path: &Path) -> Option<Vec<u8>> {     fs::read_link(path)         .ok()-        .map(|target| target.as_os_str().as_bytes().to_vec())+        .map(|target| platform::path_to_bytes(&target)) }  #[derive(Clone, Copy)]@@ -231,12 +221,10 @@     };     Some(StatInfo {         kind,-        executable: metadata.mode() & 0o111 != 0,-        size: metadata.size(),-        mtime_ns: (metadata.mtime() as u64)-            .wrapping_mul(1_000_000_000)-            .wrapping_add(metadata.mtime_nsec() as u64),-        inode: metadata.ino(),+        executable: platform::executable(&metadata),+        size: metadata.len(),+        mtime_ns: platform::mtime_ns(&metadata),+        inode: platform::inode(&metadata),     }) } @@ -495,16 +483,7 @@ }  pub fn shell_quote_arg(value: &str) -> String {-    let mut output = String::from("'");-    for character in value.chars() {-        if character == '\'' {-            output.push_str("'\\''");-        } else {-            output.push(character);-        }-    }-    output.push('\'');-    output+    platform::shell_quote(value) }  pub fn editor_command(root: &Path) -> String {@@ -527,7 +506,7 @@             return value;         }     }-    "vi".to_string()+    platform::default_editor().to_string() }  pub fn run_editor(root: &Path, paths: &[String], message_file: Option<&Path>) -> bool {@@ -540,15 +519,13 @@         command.push(' ');         command.push_str(&shell_quote_arg(&path_display(file)));     }-    std::process::Command::new("sh")-        .arg("-c")-        .arg(command)+    platform::shell(&command)         .status()         .is_ok_and(|status| status.success()) }  pub fn stdin_is_terminal() -> bool {-    unsafe { libc::isatty(libc::STDIN_FILENO) == 1 }+    platform::stdin_is_terminal() }  pub fn colors_enabled() -> bool {@@ -570,11 +547,11 @@ }  pub fn stdout_is_terminal() -> bool {-    unsafe { libc::isatty(libc::STDOUT_FILENO) == 1 }+    platform::stdout_is_terminal() }  pub fn stderr_is_terminal() -> bool {-    unsafe { libc::isatty(libc::STDERR_FILENO) == 1 }+    platform::stderr_is_terminal() }  pub fn pager_command(root: &Path) -> String {@@ -597,7 +574,7 @@             return value;         }     }-    "less -R".to_string()+    platform::default_pager().to_string() }  pub fn run_pager(root: &Path, text: &str) -> bool {@@ -615,9 +592,7 @@         pager_command(root),         shell_quote_arg(&path_display(&file))     );-    let ok = std::process::Command::new("sh")-        .arg("-c")-        .arg(command)+    let ok = platform::shell(&command)         .status()         .is_ok_and(|status| status.success());     let _ = fs::remove_file(&file);--- a/veinsrs/src/crypto.rs+++ b/veinsrs/src/crypto.rs@@ -1,5 +1,4 @@ use std::fs;-use std::os::unix::fs::PermissionsExt;  use ring::signature::KeyPair; @@ -187,7 +186,7 @@     }     let path = key_path(name);     let metadata = fs::metadata(&path).ok()?;-    if metadata.permissions().mode() & 63 != 0 {+    if crate::platform::permissions_mode(&metadata) & 63 != 0 {         return None;     }     let data = fs::read(path).ok()?;@@ -210,7 +209,7 @@     }     let directory = key_dir();     fs::create_dir_all(&directory).ok()?;-    let _ = fs::set_permissions(&directory, fs::Permissions::from_mode(0o700));+    let _ = crate::platform::set_mode(&directory, 0o700);     let seed = secure_random(32);     if seed.len() != 32 {         return None;@@ -221,7 +220,7 @@     body.extend_from_slice(&seed);     let path = key_path(name);     fs::write(&path, &body).ok()?;-    let _ = fs::set_permissions(&path, fs::Permissions::from_mode(0o600));+    let _ = crate::platform::set_mode(&path, 0o600);     Some(Key {         name: name.to_string(),         fingerprint: key_fingerprint(&public_key),@@ -413,7 +412,7 @@ pub fn load_access(repo_root: &std::path::Path) -> Access {     let path = access_path(repo_root);     if let Ok(metadata) = fs::metadata(&path)-        && metadata.permissions().mode() & 18 != 0+        && crate::platform::permissions_mode(&metadata) & 18 != 0     {         return Access {             valid: false,@@ -481,7 +480,7 @@ }  fn set_mode(path: &std::path::Path, mode: u32) {-    let _ = fs::set_permissions(path, fs::Permissions::from_mode(mode));+    let _ = crate::platform::set_mode(path, mode); }  pub fn write_access(repo_root: &std::path::Path, access: &Access) -> bool {--- a/veinsrs/src/lib.rs+++ b/veinsrs/src/lib.rs@@ -7,6 +7,7 @@ pub mod identity; pub mod merge; pub mod object;+pub mod platform; pub mod protocol; pub mod server; pub mod store;--- a/veinsrs/src/main.rs+++ b/veinsrs/src/main.rs@@ -1,6 +1,12 @@ use std::process::ExitCode;  fn main() -> ExitCode {-    let args: Vec<String> = std::env::args().skip(1).collect();+    // `std::env::args()` panics on non-UTF-8 arguments; use the lossy OS form so+    // arbitrary commit messages and revision names degrade to text instead of+    // aborting the process.+    let args: Vec<String> = std::env::args_os()+        .skip(1)+        .map(|argument| argument.to_string_lossy().into_owned())+        .collect();     ExitCode::from(veins_rust::cli::run(&args)) }--- a/veinsrs/src/merge/engine.rs+++ b/veinsrs/src/merge/engine.rs@@ -1164,10 +1164,12 @@         && sum.adds[1].kind != 0         && sum.removes[0].kind != 0         && !merge_binary(repo, path)+        && let (Some(base), Some(ours), Some(theirs)) = (+            sum.removes[0].target,+            sum.adds[0].target,+            sum.adds[1].target,+        )     {-        let base = sum.removes[0].target.unwrap();-        let ours = sum.adds[0].target.unwrap();-        let theirs = sum.adds[1].target.unwrap();         if let Some(merged) = merge_blobs(store, Some(txn.writer()), base, ours, theirs, adjacent)?         {             if !merged.conflicted {@@ -1666,12 +1668,17 @@     if ours.kind == KIND_SUBTREE || theirs.kind == KIND_SUBTREE || base.kind == KIND_SUBTREE {         return Ok(None);     }+    let (Some(base_id), Some(ours_id), Some(theirs_id)) =+        (base.target, ours.target, theirs.target)+    else {+        return Ok(None);+    };     merge_blobs(         store,         None,-        base.target.unwrap(),-        ours.target.unwrap(),-        theirs.target.unwrap(),+        base_id,+        ours_id,+        theirs_id,         adjacent,     ) }--- /dev/null+++ b/veinsrs/src/platform.rs@@ -0,0 +1,419 @@+//! Small cross-platform shims for the OS primitives the store and worktree rely on.++use std::fs::{self, File, Metadata};+use std::io;+use std::path::{Path, PathBuf};+use std::process::Command;++#[cfg(unix)]+mod imp {+    use super::*;+    use std::ffi::OsString;+    use std::os::unix::ffi::{OsStrExt, OsStringExt};+    use std::os::unix::fs::{MetadataExt, PermissionsExt};+    use std::io::IsTerminal;++    pub fn path_from_bytes(bytes: &[u8]) -> PathBuf {+        PathBuf::from(OsString::from_vec(bytes.to_vec()))+    }++    pub fn path_to_bytes(path: &Path) -> Vec<u8> {+        path.as_os_str().as_bytes().to_vec()+    }++    pub fn path_display(path: &Path) -> String {+        String::from_utf8_lossy(path.as_os_str().as_bytes()).into_owned()+    }++    pub fn os_string_from_bytes(bytes: &[u8]) -> OsString {+        OsString::from_vec(bytes.to_vec())+    }++    pub fn os_string_to_bytes(value: OsString) -> Vec<u8> {+        value.into_vec()+    }++    pub fn mtime_ns(metadata: &Metadata) -> u64 {+        (metadata.mtime() as u64)+            .wrapping_mul(1_000_000_000)+            .wrapping_add(metadata.mtime_nsec() as u64)+    }++    pub fn inode(metadata: &Metadata) -> u64 {+        metadata.ino()+    }++    pub fn executable(metadata: &Metadata) -> bool {+        metadata.mode() & 0o111 != 0+    }++    pub fn permissions_mode(metadata: &Metadata) -> u32 {+        metadata.permissions().mode()+    }++    pub fn set_mode(path: &Path, mode: u32) -> io::Result<()> {+        fs::set_permissions(path, fs::Permissions::from_mode(mode))+    }++    pub fn create_symlink(target: &Path, link: &Path) -> io::Result<()> {+        std::os::unix::fs::symlink(target, link)+    }++    pub fn sync_file(path: &Path) -> io::Result<()> {+        File::open(path)?.sync_all()+    }++    pub fn sync_directory(path: &Path) {+        if let Ok(directory) = File::open(path) {+            let _ = directory.sync_all();+        }+    }++    pub fn read_at(file: &File, buffer: &mut [u8], offset: u64) -> io::Result<usize> {+        use std::os::unix::fs::FileExt;+        file.read_at(buffer, offset)+    }++    pub fn shell(command: &str) -> Command {+        let mut process = Command::new("sh");+        process.arg("-c").arg(command);+        process+    }++    pub fn shell_quote(value: &str) -> String {+        let mut output = String::from("'");+        for character in value.chars() {+            if character == '\'' {+                output.push_str("'\\''");+            } else {+                output.push(character);+            }+        }+        output.push('\'');+        output+    }++    pub fn default_editor() -> &'static str {+        "vi"+    }++    pub fn default_pager() -> &'static str {+        "less -R"+    }++    pub fn stdin_is_terminal() -> bool {+        io::stdin().is_terminal()+    }++    pub fn stdout_is_terminal() -> bool {+        io::stdout().is_terminal()+    }++    pub fn stderr_is_terminal() -> bool {+        io::stderr().is_terminal()+    }+}++#[cfg(windows)]+mod imp {+    use super::*;+    use std::ffi::OsString;++    pub fn path_from_bytes(bytes: &[u8]) -> PathBuf {+        PathBuf::from(String::from_utf8_lossy(bytes).into_owned())+    }++    pub fn path_to_bytes(path: &Path) -> Vec<u8> {+        path.as_os_str().to_string_lossy().into_owned().into_bytes()+    }++    pub fn path_display(path: &Path) -> String {+        path.to_string_lossy().into_owned()+    }++    pub fn os_string_from_bytes(bytes: &[u8]) -> OsString {+        OsString::from(String::from_utf8_lossy(bytes).into_owned())+    }++    pub fn os_string_to_bytes(value: OsString) -> Vec<u8> {+        value.to_string_lossy().into_owned().into_bytes()+    }++    pub fn mtime_ns(metadata: &Metadata) -> u64 {+        use std::time::UNIX_EPOCH;+        metadata+            .modified()+            .ok()+            .and_then(|modified| modified.duration_since(UNIX_EPOCH).ok())+            .map(|elapsed| elapsed.as_nanos() as u64)+            .unwrap_or(0)+    }++    pub fn inode(_metadata: &Metadata) -> u64 {+        0+    }++    pub fn executable(_metadata: &Metadata) -> bool {+        false+    }++    pub fn permissions_mode(_metadata: &Metadata) -> u32 {+        0+    }++    pub fn set_mode(path: &Path, mode: u32) -> io::Result<()> {+        let mut permissions = fs::metadata(path)?.permissions();+        permissions.set_readonly(mode & 0o200 == 0);+        fs::set_permissions(path, permissions)+    }++    pub fn create_symlink(target: &Path, link: &Path) -> io::Result<()> {+        std::os::windows::fs::symlink_file(target, link)+            .or_else(|_| std::os::windows::fs::symlink_dir(target, link))+    }++    pub fn sync_file(path: &Path) -> io::Result<()> {+        File::open(path)?.sync_all()+    }++    pub fn sync_directory(_path: &Path) {}++    pub fn read_at(file: &File, buffer: &mut [u8], offset: u64) -> io::Result<usize> {+        use std::os::windows::fs::FileExt;+        file.seek_read(buffer, offset)+    }++    pub fn shell(command: &str) -> Command {+        let mut process = Command::new("cmd");+        process.arg("/C").arg(command);+        process+    }++    pub fn shell_quote(value: &str) -> String {+        let mut output = String::from("\"");+        for character in value.chars() {+            if character == '"' {+                output.push_str("\\\"");+            } else {+                output.push(character);+            }+        }+        output.push('"');+        output+    }++    pub fn default_editor() -> &'static str {+        "notepad"+    }++    pub fn default_pager() -> &'static str {+        "more"+    }++    pub fn stdin_is_terminal() -> bool {+        use std::io::IsTerminal;+        io::stdin().is_terminal()+    }++    pub fn stdout_is_terminal() -> bool {+        use std::io::IsTerminal;+        io::stdout().is_terminal()+    }++    pub fn stderr_is_terminal() -> bool {+        use std::io::IsTerminal;+        io::stderr().is_terminal()+    }+}++#[cfg(not(any(unix, windows)))]+mod imp {+    use super::*;+    use std::ffi::OsString;++    pub fn path_from_bytes(bytes: &[u8]) -> PathBuf {+        PathBuf::from(String::from_utf8_lossy(bytes).into_owned())+    }++    pub fn path_to_bytes(path: &Path) -> Vec<u8> {+        path.to_string_lossy().into_owned().into_bytes()+    }++    pub fn path_display(path: &Path) -> String {+        path.to_string_lossy().into_owned()+    }++    pub fn os_string_from_bytes(bytes: &[u8]) -> OsString {+        OsString::from(String::from_utf8_lossy(bytes).into_owned())+    }++    pub fn os_string_to_bytes(value: OsString) -> Vec<u8> {+        value.to_string_lossy().into_owned().into_bytes()+    }++    pub fn mtime_ns(_metadata: &Metadata) -> u64 {+        0+    }++    pub fn inode(_metadata: &Metadata) -> u64 {+        0+    }++    pub fn executable(_metadata: &Metadata) -> bool {+        false+    }++    pub fn permissions_mode(_metadata: &Metadata) -> u32 {+        0+    }++    pub fn set_mode(_path: &Path, _mode: u32) -> io::Result<()> {+        Ok(())+    }++    pub fn create_symlink(_target: &Path, _link: &Path) -> io::Result<()> {+        Err(io::Error::new(io::ErrorKind::Unsupported, "symlinks unavailable"))+    }++    pub fn sync_file(path: &Path) -> io::Result<()> {+        File::open(path)?.sync_all()+    }++    pub fn sync_directory(_path: &Path) {}++    pub fn read_at(file: &File, buffer: &mut [u8], offset: u64) -> io::Result<usize> {+        use std::io::{Read, Seek, SeekFrom};+        let mut file = file;+        file.seek(SeekFrom::Start(offset))?;+        file.read(buffer)+    }++    pub fn shell(command: &str) -> Command {+        let mut process = Command::new("sh");+        process.arg("-c").arg(command);+        process+    }++    pub fn shell_quote(value: &str) -> String {+        let mut output = String::from("'");+        for character in value.chars() {+            if character == '\'' {+                output.push_str("'\\''");+            } else {+                output.push(character);+            }+        }+        output.push('\'');+        output+    }++    pub fn default_editor() -> &'static str {+        "vi"+    }++    pub fn default_pager() -> &'static str {+        "less -R"+    }++    pub fn stdin_is_terminal() -> bool {+        false+    }++    pub fn stdout_is_terminal() -> bool {+        false+    }++    pub fn stderr_is_terminal() -> bool {+        false+    }+}++pub use imp::*;++/// Read-only memory mapping of a pack file, used to avoid one syscall per record.+///+/// Only Unix maps; other platforms return `None` and the store falls back to+/// positioned reads, matching the C++ implementation's behaviour.+pub struct Mapping {+    #[cfg(unix)]+    ptr: *mut libc::c_void,+    #[cfg(unix)]+    len: usize,+}++#[cfg(unix)]+unsafe impl Send for Mapping {}+#[cfg(unix)]+unsafe impl Sync for Mapping {}++impl Mapping {+    pub fn open(path: &Path) -> Option<Self> {+        #[cfg(unix)]+        {+            use std::os::unix::io::AsRawFd;+            let file = File::open(path).ok()?;+            let len = file.metadata().ok()?.len();+            if len == 0 || len as u128 > usize::MAX as u128 {+                return None;+            }+            let ptr = unsafe {+                libc::mmap(+                    std::ptr::null_mut(),+                    len as usize,+                    libc::PROT_READ,+                    libc::MAP_PRIVATE,+                    file.as_raw_fd(),+                    0,+                )+            };+            if ptr == libc::MAP_FAILED {+                return None;+            }+            Some(Mapping {+                ptr,+                len: len as usize,+            })+        }+        #[cfg(not(unix))]+        {+            let _ = path;+            None+        }+    }++    pub fn as_slice(&self) -> &[u8] {+        #[cfg(unix)]+        {+            unsafe { std::slice::from_raw_parts(self.ptr as *const u8, self.len) }+        }+        #[cfg(not(unix))]+        {+            &[]+        }+    }+}++#[cfg(unix)]+impl Drop for Mapping {+    fn drop(&mut self) {+        unsafe {+            libc::munmap(self.ptr, self.len);+        }+    }+}++/// Read only the requested window of a file into a fresh buffer.+pub fn read_range(file: &File, offset: u64, length: usize) -> Option<Vec<u8>> {+    let mut data = vec![0u8; length];+    let mut done = 0;+    while done < length {+        match read_at(file, &mut data[done..], offset + done as u64) {+            Ok(0) => break,+            Ok(count) => done += count,+            Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,+            Err(_) => return None,+        }+    }+    data.truncate(done);+    Some(data)+}--- a/veinsrs/src/server.rs+++ b/veinsrs/src/server.rs@@ -369,7 +369,14 @@         );         return true;     }-    let public_key = public_key.unwrap();+    let Some(public_key) = public_key else {+        session.stream.write_error(+            frame.request_id,+            wire::error_code::AUTH_FAILED,+            "authentication failed",+        );+        return true;+    };     session.authed = true;     session.role = role;     session.public_key = Some(public_key);--- a/veinsrs/src/store/layout.rs+++ b/veinsrs/src/store/layout.rs@@ -1,9 +1,9 @@ use std::fs::{self, File}; use std::io::Write;-use std::os::unix::io::AsRawFd; use std::path::{Path, PathBuf};  use crate::error::{Error, Result};+use crate::platform;  pub fn veins_dir(root: &Path) -> PathBuf {     root.join(".veins")@@ -124,28 +124,18 @@ }  fn sync_file(path: &Path) -> Result<()> {-    let file = File::open(path)?;-    if unsafe { libc::fsync(file.as_raw_fd()) } != 0 {-        return Err(std::io::Error::last_os_error().into());-    }-    Ok(())+    Ok(platform::sync_file(path)?) }  fn sync_directory(path: &Path) {-    if let Ok(directory) = File::open(path) {-        unsafe {-            libc::fsync(directory.as_raw_fd());-        }-    }+    platform::sync_directory(path); }  pub fn read_directory(path: &Path) -> Result<Vec<Vec<u8>>> {-    use std::os::unix::ffi::OsStringExt;-     let mut names = Vec::new();     for entry in fs::read_dir(path)? {         let entry = entry?;-        names.push(entry.file_name().into_vec());+        names.push(platform::os_string_to_bytes(entry.file_name()));     }     names.sort();     Ok(names)@@ -152,8 +142,7 @@ }  pub fn os_string(bytes: &[u8]) -> std::ffi::OsString {-    use std::os::unix::ffi::OsStringExt;-    std::ffi::OsString::from_vec(bytes.to_vec())+    platform::os_string_from_bytes(bytes) }  pub fn append_file(path: &Path, data: &[u8]) -> Result<()> {--- a/veinsrs/src/store/reader.rs+++ b/veinsrs/src/store/reader.rs@@ -1,5 +1,4 @@ use std::fs::{self, File};-use std::os::unix::fs::FileExt; use std::path::{Path, PathBuf}; use std::sync::{Mutex, OnceLock}; @@ -8,6 +7,7 @@ use crate::object::id::{Id, object_id}; use crate::object::view::{self, Operation, View}; use crate::object::{MAX_STORE_PACK_BYTES, TYPE_CHUNK, type_valid};+use crate::platform::{self, Mapping}; use crate::store::index::{self, Index}; use crate::store::layout; use crate::store::pack::{self, Pack, record_limit};@@ -46,7 +46,7 @@ fn read_at_into(file: &File, offset: u64, buffer: &mut [u8]) -> Option<usize> {     let mut done = 0;     while done < buffer.len() {-        match file.read_at(&mut buffer[done..], offset + done as u64) {+        match platform::read_at(file, &mut buffer[done..], offset + done as u64) {             Ok(0) => break,             Ok(count) => done += count,             Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue,@@ -61,6 +61,7 @@     mtime_ns: u64,     index: Option<Index>,     file: Option<File>,+    map: Option<Mapping>, }  pub struct Store {@@ -100,12 +101,7 @@                 let mtime_ns = entry                     .metadata()                     .ok()-                    .map(|metadata| {-                        use std::os::unix::fs::MetadataExt;-                        (metadata.mtime() as u64)-                            .wrapping_mul(1_000_000_000)-                            .wrapping_add(metadata.mtime_nsec() as u64)-                    })+                    .map(|metadata| platform::mtime_ns(&metadata))                     .unwrap_or(0);                 self.packs.push(PackFile {                     path,@@ -112,6 +108,7 @@                     mtime_ns,                     index: None,                     file: None,+                    map: None,                 });             }         }@@ -161,6 +158,13 @@                 true             }             Err(_) => false,+        }+    }++    fn ensure_mapping(&mut self, index: usize) {+        let pack = &mut self.packs[index];+        if pack.map.is_none() {+            pack.map = Mapping::open(&pack.path);         }     } @@ -168,7 +172,17 @@         if length as u64 > MAX_STORE_PACK_BYTES {             return None;         }-        let file = self.packs.get(index)?.file.as_ref()?;+        let pack = self.packs.get(index)?;+        if let Some(map) = &pack.map {+            let data = map.as_slice();+            let start = usize::try_from(offset).ok()?;+            if start >= data.len() {+                return None;+            }+            let end = start.saturating_add(length).min(data.len());+            return Some(data[start..end].to_vec());+        }+        let file = pack.file.as_ref()?;         let mut data = vec![0u8; length];         let done = read_at_into(file, offset, &mut data)?;         data.truncate(done);@@ -176,14 +190,27 @@     }      fn record_at(&self, pack_index: usize, offset: u64, expected: Option<Id>) -> Option<Location> {-        let mut buffer = [0u8; 96];-        let file = self.packs.get(pack_index)?.file.as_ref()?;-        let length = read_at_into(file, offset, &mut buffer)?;-        let header = &buffer[..length];+        let mut header_buffer = [0u8; 96];+        let header: &[u8] = {+            let pack = self.packs.get(pack_index)?;+            if let Some(map) = &pack.map {+                let data = map.as_slice();+                let start = usize::try_from(offset).ok()?;+                if start >= data.len() {+                    return None;+                }+                let end = start.saturating_add(header_buffer.len()).min(data.len());+                &data[start..end]+            } else {+                let file = pack.file.as_ref()?;+                let length = read_at_into(file, offset, &mut header_buffer)?;+                &header_buffer[..length]+            }+        };         if header.len() < 34 {             return None;         }-        let mut reader = Reader::new(&header);+        let mut reader = Reader::new(header);         let id = reader.id().ok()?;         let kind = reader.u8().ok()?;         let compression = reader.u8().ok()?;@@ -248,6 +275,7 @@             if !self.open_file(index) {                 continue;             }+            self.ensure_mapping(index);             if let Some(location) = self.record_at(index, offset, Some(id)) {                 return Some(location);             }@@ -303,6 +331,7 @@             return Err(Error::new("pack location out of range"));         }         self.open_file(location.pack);+        self.ensure_mapping(location.pack);         self.get_at(location, 0)     } --- a/veinsrs/src/worktree/checkout.rs+++ b/veinsrs/src/worktree/checkout.rs@@ -1,5 +1,4 @@ use std::fs;-use std::os::unix::fs::PermissionsExt; use std::path::{Path, PathBuf};  use rayon::prelude::*;@@ -10,6 +9,7 @@ use crate::object::id::Id; use crate::object::path::valid_checkout_path; use crate::object::tree::{self, FlatEntry};+use crate::platform; use crate::store::Txn; use crate::store::graph; use crate::store::layout;@@ -231,7 +231,7 @@         return Err(Error::new("cannot write checkout file"));     }     let mode = if executable { 0o755 } else { 0o644 };-    fs::set_permissions(&path, fs::Permissions::from_mode(mode))?;+    platform::set_mode(&path, mode)?;     Ok(()) } @@ -247,7 +247,7 @@         }         remove_any(&path)?;     }-    std::os::unix::fs::symlink(core::path_from_bytes(target), &path)?;+    platform::create_symlink(&core::path_from_bytes(target), &path)?;     Ok(()) } --- a/veinsrs/src/worktree/pathspec.rs+++ b/veinsrs/src/worktree/pathspec.rs@@ -1,4 +1,3 @@-use std::os::unix::ffi::OsStrExt; use std::path::Path;  use crate::core;@@ -11,7 +10,7 @@         return Some(String::new());     }     let relative = current.strip_prefix(&root).ok()?;-    Some(String::from_utf8_lossy(relative.as_os_str().as_bytes()).into_owned())+    Some(String::from_utf8_lossy(&core::path_to_bytes(relative)).into_owned()) }  fn normalize_components(input: &str) -> Option<String> {--- a/veinsrs/src/worktree/snapshot.rs+++ b/veinsrs/src/worktree/snapshot.rs@@ -178,8 +178,8 @@         let old_index = old_tree             .as_ref()             .and_then(|tree| tree::find_entry(tree, name));-        if let Some(found) = old_index-            && old_tree.as_ref().unwrap().entries[found].kind == KIND_CONFLICT+        if let (Some(found), Some(tree)) = (old_index, old_tree.as_ref())+            && tree.entries[found].kind == KIND_CONFLICT         {             plans.push(Plan {                 kind: PlanKind::Conflict,@@ -187,7 +187,7 @@                 rel: relative,                 path: directory.join(core::path_from_bytes(name)),                 info,-                target: Some(old_tree.as_ref().unwrap().entries[found].target),+                target: Some(tree.entries[found].target),                 child_old: None,                 executable: false,                 needs_read: false,@@ -217,8 +217,8 @@             trusted: false,         };         if is_dir {-            if let Some(found) = old_index {-                let entry = &old_tree.as_ref().unwrap().entries[found];+            if let (Some(found), Some(tree)) = (old_index, old_tree.as_ref()) {+                let entry = &tree.entries[found];                 if entry.kind == KIND_SUBTREE {                     plan.child_old = Some(entry.target);                 }@@ -250,7 +250,10 @@         .collect();     let job_bytes: u64 = jobs.iter().map(|index| plans[*index].info.size).sum(); -    let built: Vec<Option<blob::BlobBuild>> = if job_bytes >= 1_000_000 {+    // Spinning up rayon costs more than it saves for the small, common case;+    // only parallelise once there is enough hashing work to amortise it.+    const PARALLEL_HASH_MIN_BYTES: u64 = 32 * 1024 * 1024;+    let built: Vec<Option<blob::BlobBuild>> = if job_bytes >= PARALLEL_HASH_MIN_BYTES {         jobs.par_iter()             .map(|index| read_build(&plans[*index].path, &plans[*index].rel, attributes))             .collect()--- a/veinsrs/src/worktree/stat_cache.rs+++ b/veinsrs/src/worktree/stat_cache.rs@@ -1,10 +1,10 @@ use std::fs;-use std::os::unix::fs::MetadataExt; use std::path::Path;  use crate::encoding::{Reader, Writer}; use crate::error::Result; use crate::object::id::Id;+use crate::platform; use crate::store::layout;  #[derive(Clone)]@@ -109,7 +109,9 @@         writer.id(entry.target);     }     let path = layout::working_copy_dir(root).join("stat-cache");-    crate::core::write_atomic_name(&path, &writer.into_vec());+    // The stat cache is rebuildable; matching C++, write it without fsync so a+    // cache refresh does not pay two sync barriers.+    crate::core::write_file(&path, &writer.into_vec());     Ok(()) } @@ -130,9 +132,9 @@ ) -> bool {     let kind = file_kind(metadata);     let mtime_ns = mtime_ns(metadata);-    if entry.size != metadata.size()+    if entry.size != metadata.len()         || entry.mtime_ns != mtime_ns-        || entry.inode != metadata.ino()+        || entry.inode != platform::inode(metadata)         || entry.executable != executable         || entry.kind != kind     {@@ -154,11 +156,7 @@ }  pub fn mtime_ns(metadata: &fs::Metadata) -> u64 {-    let seconds = metadata.mtime();-    let nanoseconds = metadata.mtime_nsec();-    (seconds as u64)-        .wrapping_mul(1_000_000_000)-        .wrapping_add(nanoseconds as u64)+    platform::mtime_ns(metadata) }  pub fn file_kind(metadata: &fs::Metadata) -> u8 {@@ -173,5 +171,5 @@ }  pub fn executable(metadata: &fs::Metadata) -> bool {-    metadata.mode() & 0o111 != 0+    platform::executable(metadata) }--- a/veinsrs/tests/integration.rs+++ b/veinsrs/tests/integration.rs@@ -28,6 +28,12 @@     }      fn command(&self, arguments: &[&str], cwd: &Path) -> Output {+        let owned: Vec<std::ffi::OsString> =+            arguments.iter().map(std::ffi::OsString::from).collect();+        self.command_os(&owned, cwd)+    }++    fn command_os(&self, arguments: &[std::ffi::OsString], cwd: &Path) -> Output {         Command::new(env!("CARGO_BIN_EXE_vn"))             .args(arguments)             .current_dir(cwd)@@ -446,6 +452,39 @@             );             assert!(!text.contains("panic"), "{command} {token}: {text}");         }+    }+}++#[cfg(unix)]+#[test]+fn invalid_utf8_arguments_do_not_panic() {+    use std::ffi::OsString;+    use std::os::unix::ffi::OsStringExt;++    let f = Fixture::new();+    f.init();+    f.write("tracked.txt", "one\n");+    f.commit("initial");+    let cases = [+        vec![+            OsString::from("go"),+            OsString::from("-m"),+            OsString::from_vec(b"caf\xe9 raw \xff\xfe".to_vec()),+        ],+        vec![+            OsString::from("co"),+            OsString::from_vec(b"caf\xe9".to_vec()),+        ],+    ];+    for arguments in cases {+        let output = f.command_os(&arguments, &f.repo);+        let text = format!(+            "{}{}",+            String::from_utf8_lossy(&output.stdout),+            String::from_utf8_lossy(&output.stderr)+        );+        assert!(!text.contains("panicked"), "{arguments:?}: {text}");+        assert!(!text.contains("panic"), "{arguments:?}: {text}");     } }