From 7e3d16ad6a2f75b0e6794caeb8d3a8465713de9c Mon Sep 17 00:00:00 2001 From: Tobias Maier Date: Sat, 17 Jan 2026 18:47:25 +0100 Subject: [PATCH] feat(transmission): add length_in_bytes method to Protocol300Transmission Add a new method to calculate the byte length of Protocol300Transmission variants without converting to bytes. The method returns: - 1 byte for control characters (Ack, Enq, Eot, Nack) - 3 bytes for Init - telegram_length + 3 bytes for Message Include comprehensive unit tests for all transmission variants to ensure correct length calculation. --- src/transmission.rs | 50 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/src/transmission.rs b/src/transmission.rs index c0746c1..4295092 100644 --- a/src/transmission.rs +++ b/src/transmission.rs @@ -61,6 +61,16 @@ impl Protocol300Transmission { Self::Message(protocol300_message) => protocol300_message.to_bytes(), } } + + /// Returns the length in bytes of the transmission + #[must_use] + pub fn length_in_bytes(&self) -> usize { + match self { + Self::Ack | Self::Enq | Self::Eot | Self::Nack => 1, + Self::Init => 3, + Self::Message(protocol300_message) => (protocol300_message.telegram_length + 3).into(), + } + } } /// Errors that can occur when getting a Protocol 300 Transmission from bytes @@ -155,4 +165,44 @@ mod tests { }; assert_eq!(Protocol300Transmission::Message(message).to_bytes(), &[0x41, 0x09, 0x01, 0x01, 0x55, 0x25, 0x04, 0x07, 0x01, 0x27, 0x11, 0xC9]); } + + #[test] + fn length_in_bytes_ack() { + assert_eq!(Protocol300Transmission::Ack.length_in_bytes(), 1); + } + + #[test] + fn length_in_bytes_enq() { + assert_eq!(Protocol300Transmission::Enq.length_in_bytes(), 1); + } + + #[test] + fn length_in_bytes_eot() { + assert_eq!(Protocol300Transmission::Eot.length_in_bytes(), 1); + } + + #[test] + fn length_in_bytes_nack() { + assert_eq!(Protocol300Transmission::Nack.length_in_bytes(), 1); + } + + #[test] + fn length_in_bytes_init() { + assert_eq!(Protocol300Transmission::Init.length_in_bytes(), 3); + } + + #[test] + fn length_in_bytes_message() { + let message = Protocol300Message{ + data_address: 0x5525, + telegram_length: 0x09, + function_code: FunctionCode::VirtualREAD, + message_identifier: MessageIdentifier::Response, + data_length: 0x04, + data: vec![0x07, 0x01, 0x27, 0x11], + checksum: 0xC9 + }; + // telegram_length is 0x09, so expected length is 0x09 + 3 = 12 + assert_eq!(Protocol300Transmission::Message(message).length_in_bytes(), 12); + } }