torrust_index_backend/utils/
parse_torrent.rs

1use std::error;
2
3use serde_bencode::{de, Error};
4
5use crate::models::torrent_file::Torrent;
6
7/// Decode a Torrent from Bencoded Bytes
8///
9/// # Errors
10///
11/// This function will return an error if unable to parse bytes into torrent.
12pub fn decode_torrent(bytes: &[u8]) -> Result<Torrent, Box<dyn error::Error>> {
13    match de::from_bytes::<Torrent>(bytes) {
14        Ok(torrent) => Ok(torrent),
15        Err(e) => {
16            println!("{e:?}");
17            Err(e.into())
18        }
19    }
20}
21
22/// Encode a Torrent into Bencoded Bytes
23///
24/// # Errors
25///
26/// This function will return an error if unable to bencode torrent.
27pub fn encode_torrent(torrent: &Torrent) -> Result<Vec<u8>, Error> {
28    match serde_bencode::to_bytes(torrent) {
29        Ok(bencode_bytes) => Ok(bencode_bytes),
30        Err(e) => {
31            eprintln!("{e:?}");
32            Err(e)
33        }
34    }
35}