diff options
author | Sunil Nimmagadda <sunil@nimmagadda.net> | 2025-07-02 00:23:44 +0530 |
---|---|---|
committer | Sunil Nimmagadda <sunil@nimmagadda.net> | 2025-07-02 00:23:44 +0530 |
commit | 55c770ca23575e73ab19d1e8e36e46d3d0999349 (patch) | |
tree | e6b4c58c4882430fc58163db80536b406a6f83c2 /src | |
parent | 03add15bd1fdcbdfc062c4b1739fb7a25fd61d86 (diff) |
Write directly to the buffer instead of cursor.
Diffstat (limited to 'src')
-rw-r--r-- | src/vrrpv2.rs | 46 |
1 files changed, 24 insertions, 22 deletions
diff --git a/src/vrrpv2.rs b/src/vrrpv2.rs index 0845eee..748f266 100644 --- a/src/vrrpv2.rs +++ b/src/vrrpv2.rs @@ -1,4 +1,4 @@ -use std::io::{self, Cursor, Read, Write}; +use std::io::{self, Cursor, Read}; use std::net::Ipv4Addr; /// A VRRP version 2 packet. @@ -112,29 +112,31 @@ impl<T: AsRef<[u8]>> BytesReader for Cursor<T> { impl VRRPv2 { pub fn to_bytes(&self) -> Result<Vec<u8>, std::io::Error> { let sz = MIN_PACKET_SIZE + (self.ip_addrs.len() * 4); - let bytes: Vec<u8> = Vec::with_capacity(sz); - let mut wr = Cursor::new(bytes); - wr.write_all( - [ - VERSION_TYPE, - self.virtual_router_id, - self.priority, - self.ip_addrs.len() as u8, - self.auth_type as u8, - self.advertisement_interval, - 0x0, // checksum bits - 0x0, // checksum bits - ] - .as_ref(), - )?; - for ip in self.ip_addrs.iter() { - wr.write_all(&ip.to_bits().to_be_bytes())?; + let mut bytes: Vec<u8> = Vec::with_capacity(sz); + + // Write header + bytes.push(VERSION_TYPE); + bytes.push(self.virtual_router_id); + bytes.push(self.priority); + bytes.push(self.ip_addrs.len() as u8); + bytes.push(self.auth_type as u8); + bytes.push(self.advertisement_interval); + bytes.extend_from_slice(&[0, 0]); // Placeholder for checksum + + // Write IP addresses + for ip in &self.ip_addrs { + bytes.extend_from_slice(&ip.to_bits().to_be_bytes()); } - wr.write_all([0; 8].as_ref())?; // Authentication Data - let mut bytes = wr.into_inner(); - // Calculate the checksum and set the respective bits + + // Write auth data + bytes.extend_from_slice(&[0; 8]); + + // Calculate and set checksum let cksum = checksum(&bytes); - [bytes[6], bytes[7]] = cksum.to_be_bytes(); + let cksum_bytes = cksum.to_be_bytes(); + bytes[6] = cksum_bytes[0]; + bytes[7] = cksum_bytes[1]; + Ok(bytes) } } |