[bencode] Implement sha1 hash

This commit is contained in:
Fabian 2024-07-23 23:01:23 +02:00
parent 32650e811d
commit aa8bb213a3
2 changed files with 20 additions and 0 deletions

View File

@ -5,3 +5,7 @@ edition = "2021"
[dependencies] [dependencies]
anyhow = "1.0.86" anyhow = "1.0.86"
sha1 = "0.10.6"
[dev-dependencies]
hex-literal = "0.4.1"

View File

@ -2,6 +2,7 @@ use std::collections::HashMap;
use std::fmt::{Display, Formatter}; use std::fmt::{Display, Formatter};
use anyhow::{anyhow, ensure, Result}; use anyhow::{anyhow, ensure, Result};
use sha1::{Digest, Sha1};
/*struct FileInfo { /*struct FileInfo {
length: i64, length: i64,
@ -116,6 +117,14 @@ impl Bencode {
Ok(result) 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)>{ fn decode_type(input: &[u8]) -> Result<(Bencode, usize)>{
if input.len() == 0 { if input.len() == 0 {
return Err(anyhow!("Empty string is not valid bencode")) return Err(anyhow!("Empty string is not valid bencode"))
@ -228,8 +237,15 @@ impl Bencode {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use hex_literal::hex;
use super::*; 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] #[test]
fn test_encode_int() { fn test_encode_int() {
assert_eq!(Bencode::encode(&Bencode::Integer(42)), "i42e".as_bytes()); assert_eq!(Bencode::encode(&Bencode::Integer(42)), "i42e".as_bytes());