Skip to content

Commit

Permalink
Creates the currect bytes for as_bytes in Package.
Browse files Browse the repository at this point in the history
  • Loading branch information
Dygear committed Aug 30, 2024
1 parent cdea59b commit 95f602f
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 13 deletions.
46 changes: 34 additions & 12 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::<Header>() as u16;
length += size_of::<Address>() as u16;
length += size_of::<Identifier>() as u16;
length += size_of::<Length>() as u16;
length += 1_u16;
length += size_of::<Instruction>() as u16;
length += self.contents.payload.as_bytes().len() as u16;
length += size_of::<Sum>() as u16;

Expand Down Expand Up @@ -667,21 +663,47 @@ impl Package {
},
..Package::default()
};
package.set_address(ADDRESS);
package.len();
package.checksum();

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::<Package>(),
)
pub fn as_bytes(&mut self) -> Vec<u8, 528> {
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
}
}

Expand Down
2 changes: 1 addition & 1 deletion tests/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down

0 comments on commit 95f602f

Please sign in to comment.