aquatic_http: serialize info_hash and peer_id properly

This commit is contained in:
Joakim Frostegård 2020-07-03 14:30:00 +02:00
parent bfabd1fe57
commit 16333b5a08
2 changed files with 22 additions and 5 deletions

View file

@ -14,6 +14,7 @@ use serde_helpers::*;
pub struct PeerId( pub struct PeerId(
#[serde( #[serde(
deserialize_with = "deserialize_20_bytes", deserialize_with = "deserialize_20_bytes",
serialize_with = "serialize_20_bytes",
)] )]
pub [u8; 20] pub [u8; 20]
); );
@ -24,11 +25,13 @@ pub struct PeerId(
pub struct InfoHash( pub struct InfoHash(
#[serde( #[serde(
deserialize_with = "deserialize_20_bytes", deserialize_with = "deserialize_20_bytes",
serialize_with = "serialize_20_bytes",
)] )]
pub [u8; 20] pub [u8; 20]
); );
#[derive(Clone, Copy, Debug, Serialize)] #[derive(Clone, Copy, Debug, Serialize)]
pub struct ResponsePeer { pub struct ResponsePeer {
pub ip_address: IpAddr, pub ip_address: IpAddr,
@ -225,6 +228,13 @@ pub enum Response {
impl Response { impl Response {
pub fn to_bytes(self) -> Vec<u8> { pub fn to_bytes(self) -> Vec<u8> {
bendy::serde::to_bytes(&self).unwrap() match bendy::serde::to_bytes(&self){
Ok(bytes) => bytes,
Err(err) => {
log::error!("error encoding response: {}", err);
Vec::new()
}
}
} }
} }

View file

@ -91,6 +91,15 @@ pub fn deserialize_20_bytes<'de, D>(
} }
#[inline]
pub fn serialize_20_bytes<S>(
bytes: &[u8; 20],
serializer: S
) -> Result<S::Ok, S::Error> where S: Serializer {
serializer.serialize_bytes(bytes)
}
pub struct InfoHashVecVisitor; pub struct InfoHashVecVisitor;
@ -162,12 +171,10 @@ pub fn serialize_response_peers_compact<S>(
bytes.extend_from_slice(&peer.port.to_be_bytes()) bytes.extend_from_slice(&peer.port.to_be_bytes())
}, },
IpAddr::V6(_) => { IpAddr::V6(_) => {
continue continue;
} }
} }
} }
let text: String = bytes.into_iter().map(|byte| byte as char).collect(); serializer.serialize_bytes(&bytes)
serializer.serialize_str(&text)
} }