From aa8bb213a3f0ccddd916b0c2185d40708c0c3ea1 Mon Sep 17 00:00:00 2001 From: Faerbit Date: Tue, 23 Jul 2024 23:01:23 +0200 Subject: [PATCH] [bencode] Implement sha1 hash --- Cargo.toml | 4 ++++ src/bencode.rs | 16 ++++++++++++++++ 2 files changed, 20 insertions(+) diff --git a/Cargo.toml b/Cargo.toml index dedd3db..69ea075 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,3 +5,7 @@ edition = "2021" [dependencies] anyhow = "1.0.86" +sha1 = "0.10.6" + +[dev-dependencies] +hex-literal = "0.4.1" diff --git a/src/bencode.rs b/src/bencode.rs index 6ab6b4b..b9f9994 100644 --- a/src/bencode.rs +++ b/src/bencode.rs @@ -2,6 +2,7 @@ use std::collections::HashMap; use std::fmt::{Display, Formatter}; use anyhow::{anyhow, ensure, Result}; +use sha1::{Digest, Sha1}; /*struct FileInfo { length: i64, @@ -116,6 +117,14 @@ impl Bencode { Ok(result) } + pub fn sha1(input: &Self) -> [u8; 20] { + let mut hasher = Sha1::new(); + + hasher.update(Self::encode(input)); + + hasher.finalize().into() + } + fn decode_type(input: &[u8]) -> Result<(Bencode, usize)>{ if input.len() == 0 { return Err(anyhow!("Empty string is not valid bencode")) @@ -228,8 +237,15 @@ impl Bencode { #[cfg(test)] mod tests { + use hex_literal::hex; use super::*; + #[test] + fn test_sha1() { + assert_eq!(Bencode::sha1(&Bencode::Integer(42)), hex!("3ce69356df4222111c27b41cccf2164e6cced799")); + assert_eq!(Bencode::sha1(&Bencode::Bytes(ByteString::from_str("foo"))), hex!("a8f4559a9623f25c4d5f1155f31a2604c55e1334")); + } + #[test] fn test_encode_int() { assert_eq!(Bencode::encode(&Bencode::Integer(42)), "i42e".as_bytes());