use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
use std::path::{Path, PathBuf};
use typed_path::Utf8UnixPathBuf;
use crate::protocol::{FileKind, LinkKind, FileMeta, Frame};
use crate::sync::scanner::{FileEntry, Manifest};
use crate::{Error, Result};
pub(crate) fn file_id(path: &str) -> u64 {
let mut h = DefaultHasher::new();
path.hash(&mut h);
h.finish()
}
pub(crate) fn file_source(root: &Path, source: Option<&Path>, relative_path: &Path) -> PathBuf {
match source {
Some(path) => path.to_path_buf(),
None => root.join(relative_path),
}
}
#[expect(clippy::cast_sign_loss)]
pub(crate) fn mtime_to_wire(mtime: i64) -> u64 {
mtime as u64
}
#[expect(clippy::cast_possible_wrap)]
pub(crate) fn mtime_from_wire(mtime: u64) -> i64 {
mtime as i64
}
#[must_use]
pub(crate) fn wire_str(s: &str) -> String {
let mut out = Utf8UnixPathBuf::new();
for part in s.split('\\') {
out.push(part);
}
out.to_string()
}
pub(crate) fn file_meta_from_entry(entry: &FileEntry) -> FileMeta {
FileMeta {
path: entry.relative_path.clone(),
size: entry.size,
mtime: mtime_to_wire(entry.mtime_sec),
mtime_nsec: entry.mtime_nsec,
mode: entry.mode,
hash: entry.file_hash,
kind: entry.kind,
link_target: entry.link_target.clone(),
inode: entry.inode,
rdev: entry.rdev,
uid: entry.uid,
gid: entry.gid,
atime: mtime_to_wire(entry.atime_sec),
atime_nsec: entry.atime_nsec,
xattrs: entry.xattrs.clone(),
}
}
pub(crate) fn manifest_from_file_meta(metas: &[FileMeta]) -> Manifest {
let files: Vec<FileEntry> = metas
.iter()
.map(|m| FileEntry {
relative_path: m.path.clone(),
size: m.size,
mode: m.mode,
mtime_sec: mtime_from_wire(m.mtime),
mtime_nsec: m.mtime_nsec,
file_hash: m.hash,
kind: m.kind,
is_dir: m.kind == FileKind::Dir,
link_target: m.link_target.clone(),
link_kind: LinkKind::Symlink,
inode: m.inode,
rdev: m.rdev,
uid: m.uid,
gid: m.gid,
atime_sec: mtime_from_wire(m.atime),
atime_nsec: m.atime_nsec,
xattrs: m.xattrs.clone(),
source_path: None,
dereferenced: false,
})
.collect();
let total_bytes = files.iter().map(|f| f.size).sum();
Manifest {
root: PathBuf::from("."),
files,
total_bytes,
skipped: Vec::new(),
}
}
pub(crate) fn wire_rel(path: &std::path::Path) -> String {
wire_str(&path.to_string_lossy())
}
pub(crate) fn from_peer(frame: Frame) -> Result<Frame> {
match frame {
Frame::Error { message } => Err(Error::Other(format!("Peer error: {message}"))),
other => Ok(other),
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::Path;
#[test]
fn wire_rel_normalizes_separators() {
assert_eq!(wire_rel(Path::new("sub/file.txt")), "sub/file.txt");
assert_eq!(wire_rel(Path::new(r"sub\file.txt")), "sub/file.txt");
assert_eq!(wire_rel(Path::new("a/b/c.txt")), "a/b/c.txt");
assert_eq!(wire_rel(Path::new("top.txt")), "top.txt");
}
}