Implement Borrow<[u8]> for ByteBuf types so they can be properly used in hashmaps

This commit is contained in:
Ivan 2024-08-18 11:40:04 +02:00
parent 1414a28aaf
commit 8dc8c1e35d
3 changed files with 20 additions and 17 deletions

View file

@ -131,6 +131,18 @@ impl std::convert::AsRef<[u8]> for ByteBufOwned {
} }
} }
impl std::borrow::Borrow<[u8]> for ByteBufOwned {
fn borrow(&self) -> &[u8] {
&self.0
}
}
impl<'a> std::borrow::Borrow<[u8]> for ByteBuf<'a> {
fn borrow(&self) -> &[u8] {
self.0
}
}
impl<'a> std::ops::Deref for ByteBuf<'a> { impl<'a> std::ops::Deref for ByteBuf<'a> {
type Target = [u8]; type Target = [u8];

View file

@ -215,7 +215,7 @@ impl PeerConnectionHandler for Handler {
None => anyhow::bail!("peer does not have metadata_size"), None => anyhow::bail!("peer does not have metadata_size"),
}; };
if extended_handshake.get_msgid(b"ut_metadata").is_none() { if extended_handshake.ut_metadata().is_none() {
anyhow::bail!("peer does not support ut_metadata"); anyhow::bail!("peer does not support ut_metadata");
} }

View file

@ -47,24 +47,15 @@ impl ExtendedHandshake<ByteBuf<'static>> {
} }
} }
impl<ByteBuf: Eq + std::hash::Hash> ExtendedHandshake<ByteBuf> { impl<'a, ByteBuf> ExtendedHandshake<ByteBuf>
pub fn get_msgid(&self, msg_type: &[u8]) -> Option<u8> where
where ByteBuf: Eq + std::hash::Hash + std::borrow::Borrow<[u8]>,
ByteBuf: AsRef<[u8]>, {
{ fn get_msgid(&self, msg_type: &'a [u8]) -> Option<u8> {
self.m.iter().find_map(|(k, v)| { self.m.get(msg_type).map(|v| *v)
if k.as_ref() == msg_type {
Some(*v)
} else {
None
}
})
} }
pub fn ut_metadata(&self) -> Option<u8> pub fn ut_metadata(&self) -> Option<u8> {
where
ByteBuf: AsRef<[u8]>,
{
self.get_msgid(b"ut_metadata") self.get_msgid(b"ut_metadata")
} }
} }