Merge pull request #193 from izderadicka/borrow

Implement Borrow<[u8]> for ByteBuf types
This commit is contained in:
Igor Katson 2024-08-18 12:50:05 +01:00 committed by GitHub
commit 75c1127f37
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 24 additions and 20 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> {
type Target = [u8];

View file

@ -215,7 +215,7 @@ impl PeerConnectionHandler for Handler {
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");
}

View file

@ -10,7 +10,7 @@ use bytes::Bytes;
use clone_to_owned::CloneToOwned;
use serde::{Deserialize, Deserializer, Serialize};
use crate::MY_EXTENDED_UT_METADATA;
use crate::{EXTENDED_UT_METADATA_KEY, MY_EXTENDED_UT_METADATA};
#[derive(Deserialize, Serialize, Debug, Default)]
pub struct ExtendedHandshake<ByteBuf: Eq + std::hash::Hash> {
@ -39,7 +39,7 @@ pub struct ExtendedHandshake<ByteBuf: Eq + std::hash::Hash> {
impl ExtendedHandshake<ByteBuf<'static>> {
pub fn new() -> Self {
let mut features = HashMap::new();
features.insert(ByteBuf(b"ut_metadata"), MY_EXTENDED_UT_METADATA);
features.insert(ByteBuf(EXTENDED_UT_METADATA_KEY), MY_EXTENDED_UT_METADATA);
Self {
m: features,
..Default::default()
@ -47,25 +47,16 @@ impl ExtendedHandshake<ByteBuf<'static>> {
}
}
impl<ByteBuf: Eq + std::hash::Hash> ExtendedHandshake<ByteBuf> {
pub fn get_msgid(&self, msg_type: &[u8]) -> Option<u8>
where
ByteBuf: AsRef<[u8]>,
{
self.m.iter().find_map(|(k, v)| {
if k.as_ref() == msg_type {
Some(*v)
} else {
None
}
})
impl<'a, ByteBuf> ExtendedHandshake<ByteBuf>
where
ByteBuf: Eq + std::hash::Hash + std::borrow::Borrow<[u8]>,
{
fn get_msgid(&self, msg_type: &'a [u8]) -> Option<u8> {
self.m.get(msg_type).map(|v| *v)
}
pub fn ut_metadata(&self) -> Option<u8>
where
ByteBuf: AsRef<[u8]>,
{
self.get_msgid(b"ut_metadata")
pub fn ut_metadata(&self) -> Option<u8> {
self.get_msgid(EXTENDED_UT_METADATA_KEY)
}
}

View file

@ -44,6 +44,7 @@ const MSGID_PIECE: u8 = 7;
const MSGID_CANCEL: u8 = 8;
const MSGID_EXTENDED: u8 = 20;
pub const EXTENDED_UT_METADATA_KEY: &[u8] = b"ut_metadata";
pub const MY_EXTENDED_UT_METADATA: u8 = 3;
#[derive(Debug)]