[bencode] Change signatures

This commit is contained in:
Fabian 2024-07-24 23:24:53 +02:00
parent aa8bb213a3
commit 854858c854

View File

@ -4,24 +4,6 @@ use std::fmt::{Display, Formatter};
use anyhow::{anyhow, ensure, Result}; use anyhow::{anyhow, ensure, Result};
use sha1::{Digest, Sha1}; use sha1::{Digest, Sha1};
/*struct FileInfo {
length: i64,
path: str,
}
struct TorrentInfo {
files: Option<Vec<FileInfo>>,
length: Option<i64>,
name: str,
piece_length: i64,
pieces: Vec<str>,
}
struct Torrent {
announce: str,
info: TorrentInfo,
extra: HashMap<str, str>
}*/
#[derive(Debug, PartialEq, Eq, Hash, Clone)] #[derive(Debug, PartialEq, Eq, Hash, Clone)]
pub struct ByteString(Vec<u8>); pub struct ByteString(Vec<u8>);
@ -38,6 +20,10 @@ impl Display for ByteString {
} }
impl ByteString { impl ByteString {
pub fn to_string(&self) -> Result<String> {
let result = std::str::from_utf8(&self.0[..])?;
Ok(result.to_string())
}
#[allow(dead_code)] #[allow(dead_code)]
pub fn from_str(input: &str) -> Self { pub fn from_str(input: &str) -> Self {
ByteString(input.as_bytes().to_vec()) ByteString(input.as_bytes().to_vec())
@ -87,14 +73,14 @@ impl Display for Bencode {
impl Bencode { impl Bencode {
pub fn encode(input: &Self) -> Vec<u8> { pub fn encode(&self) -> Vec<u8> {
match input { match self {
Bencode::Integer(i) => {format!("i{}e", i).as_bytes().to_vec()} Bencode::Integer(i) => {format!("i{}e", i).as_bytes().to_vec()}
Bencode::Bytes(b) => {[format!("{}:", b.0.len()).as_bytes(), &b.0[..]].concat()} Bencode::Bytes(b) => {[format!("{}:", b.0.len()).as_bytes(), &b.0[..]].concat()}
Bencode::List(l) => { Bencode::List(l) => {
let mut result = vec!['l' as u8]; let mut result = vec!['l' as u8];
for item in l { for item in l {
result.extend(Self::encode(item)) result.extend(item.encode())
} }
result.push('e' as u8); result.push('e' as u8);
result result
@ -103,7 +89,7 @@ impl Bencode {
let mut result = vec!['d' as u8]; let mut result = vec!['d' as u8];
for (k, v) in d { for (k, v) in d {
result.extend(Self::encode(&Bencode::Bytes(k.clone()))); result.extend(Self::encode(&Bencode::Bytes(k.clone())));
result.extend(Self::encode(v)); result.extend(v.encode());
} }
result.push('e' as u8); result.push('e' as u8);
result result
@ -117,10 +103,10 @@ impl Bencode {
Ok(result) Ok(result)
} }
pub fn sha1(input: &Self) -> [u8; 20] { pub fn sha1(&self) -> [u8; 20] {
let mut hasher = Sha1::new(); let mut hasher = Sha1::new();
hasher.update(Self::encode(input)); hasher.update(self.encode());
hasher.finalize().into() hasher.finalize().into()
} }
@ -242,30 +228,30 @@ mod tests {
#[test] #[test]
fn test_sha1() { fn test_sha1() {
assert_eq!(Bencode::sha1(&Bencode::Integer(42)), hex!("3ce69356df4222111c27b41cccf2164e6cced799")); assert_eq!(Bencode::Integer(42).sha1(), hex!("3ce69356df4222111c27b41cccf2164e6cced799"));
assert_eq!(Bencode::sha1(&Bencode::Bytes(ByteString::from_str("foo"))), hex!("a8f4559a9623f25c4d5f1155f31a2604c55e1334")); assert_eq!(Bencode::Bytes(ByteString::from_str("foo")).sha1(), hex!("a8f4559a9623f25c4d5f1155f31a2604c55e1334"));
} }
#[test] #[test]
fn test_encode_int() { fn test_encode_int() {
assert_eq!(Bencode::encode(&Bencode::Integer(42)), "i42e".as_bytes()); assert_eq!(Bencode::Integer(42).encode(), "i42e".as_bytes());
assert_eq!(Bencode::encode(&Bencode::Integer(17)), "i17e".as_bytes()); assert_eq!(Bencode::Integer(17).encode(), "i17e".as_bytes());
} }
#[test] #[test]
fn test_encode_bytes() { fn test_encode_bytes() {
assert_eq!(Bencode::encode(&Bencode::Bytes(ByteString::from_str("foo"))), "3:foo".as_bytes()); assert_eq!(Bencode::Bytes(ByteString::from_str("foo")).encode(), "3:foo".as_bytes());
assert_eq!(Bencode::encode(&Bencode::Bytes(ByteString::from_str("bar"))), "3:bar".as_bytes()); assert_eq!(Bencode::Bytes(ByteString::from_str("bar")).encode(), "3:bar".as_bytes());
} }
#[test] #[test]
fn test_encode_list() { fn test_encode_list() {
assert_eq!(Bencode::encode(&Bencode::List(vec![Bencode::Bytes(ByteString::from_str("foo")), Bencode::Integer(42)])), "l3:fooi42ee".as_bytes()); assert_eq!(Bencode::List(vec![Bencode::Bytes(ByteString::from_str("foo")), Bencode::Integer(42)]).encode(), "l3:fooi42ee".as_bytes());
} }
#[test] #[test]
fn test_encode_dict() { fn test_encode_dict() {
assert_eq!(Bencode::encode(&Bencode::Dict(HashMap::from([(ByteString::from_str("foo"), Bencode::Integer(42))]))), "d3:fooi42ee".as_bytes()); assert_eq!(Bencode::Dict(HashMap::from([(ByteString::from_str("foo"), Bencode::Integer(42))])).encode(), "d3:fooi42ee".as_bytes());
} }
#[test] #[test]