switch from copy_from_slice to Cursor for serialising responses

This commit is contained in:
Adam 2025-08-07 21:51:43 +01:00
parent 478ce597a7
commit 636ba8d7f5

View File

@ -106,48 +106,48 @@ pub struct AnnounceResponseV6 {
impl AnnounceResponseCommon {
pub fn write_to_buf(&self, buf: &mut [u8]) -> usize {
const ACTION: i32 = Action::Announce as i32;
buf[0..4].copy_from_slice(&ACTION.to_be_bytes());
buf[4..8].copy_from_slice(&self.transaction_id.to_be_bytes());
buf[8..12].copy_from_slice(&self.interval.to_be_bytes());
buf[12..16].copy_from_slice(&self.leechers.to_be_bytes());
buf[16..20].copy_from_slice(&self.seeders.to_be_bytes());
let mut c = Cursor::new(buf);
let mut written: usize = 0;
return MIN_ANNOUNCE_RESPONSE_SIZE;
const ACTION: i32 = Action::Announce as i32;
written += c.write(&ACTION.to_be_bytes()).unwrap();
written += c.write(&self.transaction_id.to_be_bytes()).unwrap();
written += c.write(&self.interval.to_be_bytes()).unwrap();
written += c.write(&self.leechers.to_be_bytes()).unwrap();
written += c.write(&self.seeders.to_be_bytes()).unwrap();
return written;
}
}
impl AnnounceResponseV4 {
pub fn write_to_buf(&self, buf: &mut [u8]) -> usize {
let written = self.common.write_to_buf(buf);
let mut written = self.common.write_to_buf(buf);
let mut c = Cursor::new(buf);
c.set_position(written as u64);
for (offset, addr) in (written..buf.len())
.step_by(IPV4_ADDR_PAIR_SIZE)
.zip(&self.peers)
{
buf[offset..offset + IPV4_SIZE].copy_from_slice(&addr.ip().octets());
buf[offset + IPV4_SIZE..offset + IPV4_ADDR_PAIR_SIZE]
.copy_from_slice(&addr.port().to_be_bytes());
for peer in &self.peers {
written += c.write(&peer.ip().octets()).unwrap();
written += c.write(&peer.port().to_be_bytes()).unwrap();
}
return written + self.peers.len() * IPV4_ADDR_PAIR_SIZE;
return written;
}
}
impl AnnounceResponseV6 {
pub fn write_to_buf(&self, buf: &mut [u8]) -> usize {
let written = self.common.write_to_buf(buf);
let mut written = self.common.write_to_buf(buf);
let mut c = Cursor::new(buf);
c.set_position(written as u64);
for (offset, addr) in (written..buf.len())
.step_by(IPV6_ADDR_PAIR_SIZE)
.zip(&self.peers)
{
buf[offset..offset + IPV6_SIZE].copy_from_slice(&addr.ip().octets());
buf[offset + IPV6_SIZE..offset + IPV6_ADDR_PAIR_SIZE]
.copy_from_slice(&addr.port().to_be_bytes());
for peer in &self.peers {
written += c.write(&peer.ip().octets()).unwrap();
written += c.write(&peer.port().to_be_bytes()).unwrap();
}
return written + self.peers.len() * IPV6_ADDR_PAIR_SIZE;
return written;
}
}