|
| 1 | +use std::panic::Location; |
| 2 | + |
| 3 | +use thiserror::Error; |
| 4 | + |
| 5 | +/// `BitTorrent` Info Hash v1 |
| 6 | +#[derive(PartialEq, Eq, Hash, Clone, Copy, Default, Debug)] |
| 7 | +pub struct InfoHash(pub [u8; 20]); |
| 8 | + |
| 9 | +pub const INFO_HASH_BYTES_LEN: usize = 20; |
| 10 | + |
| 11 | +impl InfoHash { |
| 12 | + /// Create a new `InfoHash` from a byte slice. |
| 13 | + /// |
| 14 | + /// # Panics |
| 15 | + /// |
| 16 | + /// Will panic if byte slice does not contains the exact amount of bytes need for the `InfoHash`. |
| 17 | + #[must_use] |
| 18 | + pub fn from_bytes(bytes: &[u8]) -> Self { |
| 19 | + assert_eq!(bytes.len(), INFO_HASH_BYTES_LEN); |
| 20 | + let mut ret = Self([0u8; INFO_HASH_BYTES_LEN]); |
| 21 | + ret.0.clone_from_slice(bytes); |
| 22 | + ret |
| 23 | + } |
| 24 | + |
| 25 | + /// Returns the `InfoHash` internal byte array. |
| 26 | + #[must_use] |
| 27 | + pub fn bytes(&self) -> [u8; 20] { |
| 28 | + self.0 |
| 29 | + } |
| 30 | + |
| 31 | + /// Returns the `InfoHash` as a hex string. |
| 32 | + #[must_use] |
| 33 | + pub fn to_hex_string(&self) -> String { |
| 34 | + self.to_string() |
| 35 | + } |
| 36 | +} |
| 37 | + |
| 38 | +impl Ord for InfoHash { |
| 39 | + fn cmp(&self, other: &Self) -> std::cmp::Ordering { |
| 40 | + self.0.cmp(&other.0) |
| 41 | + } |
| 42 | +} |
| 43 | + |
| 44 | +impl std::cmp::PartialOrd<InfoHash> for InfoHash { |
| 45 | + fn partial_cmp(&self, other: &InfoHash) -> Option<std::cmp::Ordering> { |
| 46 | + Some(self.cmp(other)) |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +impl std::fmt::Display for InfoHash { |
| 51 | + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 52 | + let mut chars = [0u8; 40]; |
| 53 | + binascii::bin2hex(&self.0, &mut chars).expect("failed to hexlify"); |
| 54 | + write!(f, "{}", std::str::from_utf8(&chars).unwrap()) |
| 55 | + } |
| 56 | +} |
| 57 | + |
| 58 | +impl std::str::FromStr for InfoHash { |
| 59 | + type Err = binascii::ConvertError; |
| 60 | + |
| 61 | + fn from_str(s: &str) -> Result<Self, Self::Err> { |
| 62 | + let mut i = Self([0u8; 20]); |
| 63 | + if s.len() != 40 { |
| 64 | + return Err(binascii::ConvertError::InvalidInputLength); |
| 65 | + } |
| 66 | + binascii::hex2bin(s.as_bytes(), &mut i.0)?; |
| 67 | + Ok(i) |
| 68 | + } |
| 69 | +} |
| 70 | + |
| 71 | +impl std::convert::From<&[u8]> for InfoHash { |
| 72 | + fn from(data: &[u8]) -> InfoHash { |
| 73 | + assert_eq!(data.len(), 20); |
| 74 | + let mut ret = InfoHash([0u8; 20]); |
| 75 | + ret.0.clone_from_slice(data); |
| 76 | + ret |
| 77 | + } |
| 78 | +} |
| 79 | + |
| 80 | +impl std::convert::From<[u8; 20]> for InfoHash { |
| 81 | + fn from(val: [u8; 20]) -> Self { |
| 82 | + InfoHash(val) |
| 83 | + } |
| 84 | +} |
| 85 | + |
| 86 | +/// Errors that can occur when converting from a `Vec<u8>` to an `InfoHash`. |
| 87 | +#[derive(Error, Debug)] |
| 88 | +pub enum ConversionError { |
| 89 | + /// Not enough bytes for infohash. An infohash is 20 bytes. |
| 90 | + #[error("not enough bytes for infohash: {message} {location}")] |
| 91 | + NotEnoughBytes { |
| 92 | + location: &'static Location<'static>, |
| 93 | + message: String, |
| 94 | + }, |
| 95 | + /// Too many bytes for infohash. An infohash is 20 bytes. |
| 96 | + #[error("too many bytes for infohash: {message} {location}")] |
| 97 | + TooManyBytes { |
| 98 | + location: &'static Location<'static>, |
| 99 | + message: String, |
| 100 | + }, |
| 101 | +} |
| 102 | + |
| 103 | +impl TryFrom<Vec<u8>> for InfoHash { |
| 104 | + type Error = ConversionError; |
| 105 | + |
| 106 | + fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> { |
| 107 | + if bytes.len() < INFO_HASH_BYTES_LEN { |
| 108 | + return Err(ConversionError::NotEnoughBytes { |
| 109 | + location: Location::caller(), |
| 110 | + message: format! {"got {} bytes, expected {}", bytes.len(), INFO_HASH_BYTES_LEN}, |
| 111 | + }); |
| 112 | + } |
| 113 | + if bytes.len() > INFO_HASH_BYTES_LEN { |
| 114 | + return Err(ConversionError::TooManyBytes { |
| 115 | + location: Location::caller(), |
| 116 | + message: format! {"got {} bytes, expected {}", bytes.len(), INFO_HASH_BYTES_LEN}, |
| 117 | + }); |
| 118 | + } |
| 119 | + Ok(Self::from_bytes(&bytes)) |
| 120 | + } |
| 121 | +} |
| 122 | + |
| 123 | +impl serde::ser::Serialize for InfoHash { |
| 124 | + fn serialize<S: serde::ser::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { |
| 125 | + let mut buffer = [0u8; 40]; |
| 126 | + let bytes_out = binascii::bin2hex(&self.0, &mut buffer).ok().unwrap(); |
| 127 | + let str_out = std::str::from_utf8(bytes_out).unwrap(); |
| 128 | + serializer.serialize_str(str_out) |
| 129 | + } |
| 130 | +} |
| 131 | + |
| 132 | +impl<'de> serde::de::Deserialize<'de> for InfoHash { |
| 133 | + fn deserialize<D: serde::de::Deserializer<'de>>(des: D) -> Result<Self, D::Error> { |
| 134 | + des.deserialize_str(InfoHashVisitor) |
| 135 | + } |
| 136 | +} |
| 137 | + |
| 138 | +struct InfoHashVisitor; |
| 139 | + |
| 140 | +impl<'v> serde::de::Visitor<'v> for InfoHashVisitor { |
| 141 | + type Value = InfoHash; |
| 142 | + |
| 143 | + fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 144 | + write!(formatter, "a 40 character long hash") |
| 145 | + } |
| 146 | + |
| 147 | + fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<Self::Value, E> { |
| 148 | + if v.len() != 40 { |
| 149 | + return Err(serde::de::Error::invalid_value( |
| 150 | + serde::de::Unexpected::Str(v), |
| 151 | + &"a 40 character long string", |
| 152 | + )); |
| 153 | + } |
| 154 | + |
| 155 | + let mut res = InfoHash([0u8; 20]); |
| 156 | + |
| 157 | + if binascii::hex2bin(v.as_bytes(), &mut res.0).is_err() { |
| 158 | + return Err(serde::de::Error::invalid_value( |
| 159 | + serde::de::Unexpected::Str(v), |
| 160 | + &"a hexadecimal string", |
| 161 | + )); |
| 162 | + }; |
| 163 | + Ok(res) |
| 164 | + } |
| 165 | +} |
0 commit comments