use serde::{Deserialize, Serialize};
use std::str::FromStr;
use crate::{InfoHash, InfoHashError};
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "sea_orm", derive(sea_orm::DeriveValueType))]
pub struct TorrentID(String);
impl TorrentID {
pub fn new<T: AsRef<str>>(s: T) -> Result<TorrentID, InfoHashError> {
Self::from_str(s.as_ref())
}
pub fn from_infohash(hash: &InfoHash) -> TorrentID {
match hash {
InfoHash::V1(v2hash) => TorrentID(v2hash.to_string()),
InfoHash::V2(v2hash) | InfoHash::Hybrid((_, v2hash)) => {
let mut truncated = v2hash.to_string();
truncated.truncate(40);
TorrentID(truncated)
}
}
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl std::fmt::Display for TorrentID {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
impl AsRef<str> for TorrentID {
fn as_ref(&self) -> &str {
&self.0
}
}
impl FromStr for TorrentID {
type Err = InfoHashError;
fn from_str(s: &str) -> Result<TorrentID, InfoHashError> {
let hash = InfoHash::new(s)?;
Ok(Self::from_infohash(&hash))
}
}