diff --git a/src/lib.rs b/src/lib.rs index 22d5bcd..8f56ded 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -611,11 +611,7 @@ impl Package { /// Sets the length of the package in bytes, and returns the same. pub fn len(&mut self) -> Length { let mut length: Length = 0; - length += size_of::
() as u16; - length += size_of::
() as u16; - length += size_of::() as u16; - length += size_of::() as u16; - length += 1_u16; + length += size_of::() as u16; length += self.contents.payload.as_bytes().len() as u16; length += size_of::() as u16; @@ -667,7 +663,6 @@ impl Package { }, ..Package::default() }; - package.set_address(ADDRESS); package.len(); package.checksum(); @@ -675,13 +670,40 @@ impl Package { } /// Get the bytes of the struct cleanly. - pub fn as_bytes(&self) -> &[u8] { - unsafe { - core::slice::from_raw_parts( - self as *const Self as *const u8, - core::mem::size_of::(), - ) + pub fn as_bytes(&mut self) -> Vec { + let mut bytes = Vec::new(); + + // Header + let data = self.header.to_be_bytes(); + for byte in data { + let _ = bytes.push(byte); + } + // Address + let data = self.address.to_be_bytes(); + for byte in data { + let _ = bytes.push(byte); + } + // Identifier + let _ = bytes.push(self.identifier as u8); + // Length + let data = self.len().to_be_bytes(); + for byte in data { + let _ = bytes.push(byte); + } + // Contents - Instruction + let _ = bytes.push(self.contents.instruction as u8); + // Contents - Payload + let data = self.contents.payload.as_bytes(); + for byte in data { + let _ = bytes.push(byte); } + // Checksum + let data = self.checksum().to_be_bytes(); + for byte in data { + let _ = bytes.push(byte); + } + + bytes } } diff --git a/tests/tests.rs b/tests/tests.rs index 7a3fcad..819ac2d 100644 --- a/tests/tests.rs +++ b/tests/tests.rs @@ -19,7 +19,7 @@ fn checksum_templete_num() { #[test] fn checksum_templete_packet() { - let package = Package::build( + let mut package = Package::build( Identifier::Command, Instruction::TempleteNum, Payload::TempleteNum,