From aafa2bc9f91c3ae7d88607bf545d9665d50fc0db Mon Sep 17 00:00:00 2001 From: Vinzenz Schroeter Date: Sat, 12 Apr 2025 11:32:28 +0200 Subject: [PATCH] copy packet to slice --- src/packet.rs | 49 +++++++++++++++++++++++++++---------------------- 1 file changed, 27 insertions(+), 22 deletions(-) diff --git a/src/packet.rs b/src/packet.rs index 1579e9d..c69a5dd 100644 --- a/src/packet.rs +++ b/src/packet.rs @@ -32,6 +32,8 @@ use std::{mem::size_of, num::TryFromIntError}; /// payload, where applicable. /// /// Because the meaning of most fields depend on the command, there are no speaking names for them. +/// +/// The contained values are in platform endian-ness and may need to be converted before sending. #[derive(Copy, Clone, Debug, PartialEq, Default)] #[repr(C)] pub struct Header { @@ -68,28 +70,9 @@ pub struct Packet { impl From for Vec { /// Turn the packet into raw bytes ready to send fn from(value: Packet) -> Self { - let Packet { - header: - Header { - command_code: mode, - a, - b, - c, - d, - }, - payload, - } = value; - - let mut packet = vec![0u8; 10 + payload.len()]; - packet[0..=1].copy_from_slice(&u16::to_be_bytes(mode)); - packet[2..=3].copy_from_slice(&u16::to_be_bytes(a)); - packet[4..=5].copy_from_slice(&u16::to_be_bytes(b)); - packet[6..=7].copy_from_slice(&u16::to_be_bytes(c)); - packet[8..=9].copy_from_slice(&u16::to_be_bytes(d)); - - packet[10..].copy_from_slice(&payload); - - packet + let mut vec = vec![0u8; 10 + value.payload.len()]; + value.copy_to(vec.as_mut_slice()); + vec } } @@ -137,6 +120,28 @@ impl TryFrom> for Packet { } impl Packet { + pub fn copy_to(&self, slice: &mut [u8]) { + let Packet { + header: + Header { + command_code, + a, + b, + c, + d, + }, + payload, + } = self; + + slice[0..=1].copy_from_slice(&u16::to_be_bytes(*command_code)); + slice[2..=3].copy_from_slice(&u16::to_be_bytes(*a)); + slice[4..=5].copy_from_slice(&u16::to_be_bytes(*b)); + slice[6..=7].copy_from_slice(&u16::to_be_bytes(*c)); + slice[8..=9].copy_from_slice(&u16::to_be_bytes(*d)); + + slice[10..].copy_from_slice(&payload); + } + fn u16_from_be_slice(slice: &[u8]) -> u16 { let mut bytes = [0u8; 2]; bytes[0] = slice[0];