commit 3d0f1875a8703b5d29491bfa5b6ad1bedbbdc778 Author: Faerbit Date: Sun Jul 21 12:46:10 2024 +0200 Initial commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..6f1a4de --- /dev/null +++ b/.gitignore @@ -0,0 +1,132 @@ +/target + +# Created by https://www.toptal.com/developers/gitignore/api/rust,jetbrains+all,vim +# Edit at https://www.toptal.com/developers/gitignore?templates=rust,jetbrains+all,vim + +### JetBrains+all ### +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/**/usage.statistics.xml +.idea/**/dictionaries +.idea/**/shelf + +# AWS User-specific +.idea/**/aws.xml + +# Generated files +.idea/**/contentModel.xml + +# Sensitive or high-churn files +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml +.idea/**/dbnavigator.xml + +# Gradle +.idea/**/gradle.xml +.idea/**/libraries + +# Gradle and Maven with auto-import +# When using Gradle or Maven with auto-import, you should exclude module files, +# since they will be recreated, and may cause churn. Uncomment if using +# auto-import. +# .idea/artifacts +# .idea/compiler.xml +# .idea/jarRepositories.xml +# .idea/modules.xml +# .idea/*.iml +# .idea/modules +# *.iml +# *.ipr + +# CMake +cmake-build-*/ + +# Mongo Explorer plugin +.idea/**/mongoSettings.xml + +# File-based project format +*.iws + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# SonarLint plugin +.idea/sonarlint/ + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +# Editor-based Rest Client +.idea/httpRequests + +# Android studio 3.1+ serialized cache file +.idea/caches/build_file_checksums.ser + +### JetBrains+all Patch ### +# Ignore everything but code style settings and run configurations +# that are supposed to be shared within teams. + +.idea/* + +!.idea/codeStyles +!.idea/runConfigurations + +### Rust ### +# Generated by Cargo +# will have compiled files and executables +debug/ +target/ + +# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries +# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html +Cargo.lock + +# These are backup files generated by rustfmt +**/*.rs.bk + +# MSVC Windows builds of rustc generate these, which store debugging information +*.pdb + +### Vim ### +# Swap +[._]*.s[a-v][a-z] +!*.svg # comment out if you don't need vector files +[._]*.sw[a-p] +[._]s[a-rt-v][a-z] +[._]ss[a-gi-z] +[._]sw[a-p] + +# Session +Session.vim +Sessionx.vim + +# Temporary +.netrwhist +*~ +# Auto-generated tag files +tags +# Persistent undo +[._]*.un~ + +# End of https://www.toptal.com/developers/gitignore/api/rust,jetbrains+all,vim + diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..dedd3db --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "torrent-rs" +version = "0.1.0" +edition = "2021" + +[dependencies] +anyhow = "1.0.86" diff --git a/src/bencode.rs b/src/bencode.rs new file mode 100644 index 0000000..7656630 --- /dev/null +++ b/src/bencode.rs @@ -0,0 +1,116 @@ +use std::collections::HashMap; + +use anyhow::{anyhow, Result}; + +/*struct FileInfo { + length: i64, + path: str, +} + +struct TorrentInfo { + files: Option>, + length: Option, + name: str, + piece_length: i64, + pieces: Vec, +} + +struct Torrent { + announce: str, + info: TorrentInfo, + extra: HashMap +}*/ + +#[derive(Debug, PartialEq, Eq, Hash)] +pub struct ByteString(Vec); + +#[derive(Debug, PartialEq)] +pub enum Bencode { + Integer(i64), + Bytes(ByteString), + List(Vec), + Dict(HashMap), +} + +#[derive(Debug, PartialEq)] +enum BencodeType { + Integer, + Bytes, + List, + Dict, +} + +impl Bencode { + pub fn decode(input: &str) -> Result { + Self::decode_slice(input.as_bytes()) + } + + fn decode_slice(input: &[u8]) -> Result{ + if input.len() == 0 { + return Err(anyhow!("Empty string is not valid bencode")); + } + let char = input[0] as char; + // let type_ = match char { + // 'i' => Ok(Discriminant(Bencode::Integer)), + // 'l' => Ok(Discriminant(Bencode::List)), + // 'd' => Ok(Discriminant(Bencode::Dict)), + // '0'..='9' => Ok(Discriminant(Bencode::Integer)), + // _ => Err(anyhow!("Unknown bencoding char: {char}")), + // }?; + let type_ = match char { + 'i' => Ok(BencodeType::Integer), + 'l' => Ok(BencodeType::List), + 'd' => Ok(BencodeType::Dict), + '0'..='9' => Ok(BencodeType::Bytes), + _ => Err(anyhow!("Unknown bencoding char: {char}")), + }?; + let end_char = match type_ { + BencodeType::Integer | BencodeType::List | BencodeType::Dict=> 'e', + BencodeType::Bytes => ':' + }; + let mut end_pos = 1; + for &c in &input[1..] { + if c == end_char as u8 { + break + } + end_pos += 1; + } + match type_ { + BencodeType::Integer => Self::decode_int(&input[1..end_pos]), + BencodeType::List => Self::dummy(), + BencodeType::Dict => Self::dummy(), + BencodeType::Bytes => Self::dummy(), + } + } + + fn decode_int(input: &[u8]) -> Result { + let int_str = std::str::from_utf8(input)?; + let int = int_str.parse::()?; + Ok(Bencode::Integer(int)) + } + + fn dummy() -> Result { + Ok(Bencode::Integer(42)) + } +} + +#[cfg(test)] +mod tests { + // Note this useful idiom: importing names from outer (for mod tests) scope. + use super::*; + + #[test] + fn test_integer() { + assert_eq!(Bencode::decode_int("42".as_bytes()).unwrap(), Bencode::Integer(42)); + assert_eq!(Bencode::decode_int("17".as_bytes()).unwrap(), Bencode::Integer(17)); + assert_eq!(Bencode::decode_int("-17".as_bytes()).unwrap(), Bencode::Integer(-17)); + } + + #[test] + fn test_integer_str() { + assert_eq!(Bencode::decode("i42e").unwrap(), Bencode::Integer(42)); + assert_eq!(Bencode::decode("i17e").unwrap(), Bencode::Integer(17)); + assert_eq!(Bencode::decode("i-17e").unwrap(), Bencode::Integer(-17)); + } + +} diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..49def53 --- /dev/null +++ b/src/main.rs @@ -0,0 +1,5 @@ +mod bencode; + +fn main() { + println!("Hello, world!"); +} diff --git a/test/Fedora-Workstation-Live-x86_64-40.torrent b/test/Fedora-Workstation-Live-x86_64-40.torrent new file mode 100644 index 0000000..478f684 Binary files /dev/null and b/test/Fedora-Workstation-Live-x86_64-40.torrent differ