torrentdht 0.1.1

DHT discovery with mTLS handshake handoff; optional BitTorrent when the host opts in
Documentation
//! Selective download: map file paths to piece indices.

use std::collections::HashSet;
use std::path::Path;

use crate::torrent::TorrentInfo;

pub fn pieces_for_selected_files(info: &TorrentInfo, patterns: &[String]) -> HashSet<u32> {
    if patterns.is_empty() {
        return (0..info.piece_count()).collect();
    }
    let mut out = HashSet::new();
    let piece_len = info.piece_length as u64;
    let mut offset = 0u64;
    for (path, len) in &info.files {
        let rel = path
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or("");
        let full = path.to_string_lossy();
        let selected = patterns.iter().any(|pat| path_selected(pat, path, rel, &full));
        if selected {
            let start_piece = (offset / piece_len) as u32;
            let end_piece = if *len == 0 {
                start_piece
            } else {
                ((offset + len - 1) / piece_len) as u32
            };
            for piece in start_piece..=end_piece.min(info.piece_count().saturating_sub(1)) {
                out.insert(piece);
            }
        }
        offset = offset.saturating_add(*len);
    }
    out
}

fn path_selected(pattern: &str, path: &Path, basename: &str, full: &str) -> bool {
    if pattern.contains('*') {
        return glob_match(pattern, basename) || glob_match(pattern, full);
    }
    if basename == pattern || full == pattern {
        return true;
    }
    // Exact path-component equality (not substring ends_with).
    let pat = std::ffi::OsStr::new(pattern);
    path.components().any(|c| {
        matches!(c, std::path::Component::Normal(part) if part == pat)
    }) || Path::new(full)
        .components()
        .any(|c| matches!(c, std::path::Component::Normal(part) if part == pat))
}

fn glob_match(pattern: &str, text: &str) -> bool {
    if pattern.contains('*') {
        let parts: Vec<&str> = pattern.split('*').collect();
        if parts.is_empty() {
            return true;
        }
        let mut pos = 0usize;
        for (idx, part) in parts.iter().enumerate() {
            if part.is_empty() {
                continue;
            }
            if idx == 0 {
                if !text.starts_with(part) {
                    return false;
                }
                pos = part.len();
            } else if idx == parts.len() - 1 {
                if !text[pos..].ends_with(part) {
                    return false;
                }
            } else if let Some(found) = text[pos..].find(part) {
                pos += found + part.len();
            } else {
                return false;
            }
        }
        true
    } else {
        text == pattern
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::torrent::{InfoHash, MetaVersion, TorrentInfo};
    use std::path::PathBuf;

    fn sample_info() -> TorrentInfo {
        TorrentInfo {
            info_hash: InfoHash::from_bytes([0; 20]),
            info_hash_v2: None,
            name: "dir".into(),
            piece_length: 10,
            pieces: vec![[0; 20]; 3],
            files: vec![
                (PathBuf::from("dir/a.txt"), 10),
                (PathBuf::from("dir/b.txt"), 10),
            ],
            total_len: 20,
            private: false,
            meta_version: MetaVersion::V1,
            v2: None,
        }
    }

    #[test]
    fn selects_file_pieces() {
        let info = sample_info();
        let pieces = pieces_for_selected_files(&info, &["a.txt".into()]);
        assert_eq!(pieces, HashSet::from([0]));
    }

    #[test]
    fn empty_patterns_selects_all() {
        let info = sample_info();
        let pieces = pieces_for_selected_files(&info, &[]);
        assert_eq!(pieces.len(), 3);
    }
}