Skip to content

Commit

Permalink
build: binder: Improve try_from vec
Browse files Browse the repository at this point in the history
Signed-off-by: Patrick José Pereira <[email protected]>
  • Loading branch information
patrickelectric committed May 16, 2024
1 parent 7e9a396 commit 8c84d90
Showing 1 changed file with 15 additions and 0 deletions.
15 changes: 15 additions & 0 deletions build/binder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -105,12 +105,27 @@ pub fn generate<W: Write>(modules: Vec<String>, out: &mut W) {
type Error = String; // TODO: define error types for each kind of failure

fn try_from(buffer: &Vec<u8>) -> Result<Self, Self::Error> {
const MIN_MSG_SIZE: usize = 10;

// Parse start1 and start2
if !((buffer[0] == HEADER[0]) && (buffer[1] == HEADER[1])) {
return Err(format!("Message should start with \"BR\" ASCII sequence, received: [{0}({:0x}), {1}({:0x})]", buffer[0], buffer[1]));
}

let buffer_size = buffer.len();
if buffer.len() < MIN_MSG_SIZE {
return Err(format!("Message is too short, should be at least {} bytes", MIN_MSG_SIZE).into());
}

let payload_length = u16::from_le_bytes([buffer[2], buffer[3]]);
if payload_length as usize + MIN_MSG_SIZE != buffer.len() {
return Err(format!(
"Payload length does not match, expected: {}, received: {}",
payload_length,
buffer.len() - MIN_MSG_SIZE
));
}

let protocol_message = ProtocolMessage {
payload_length,
message_id: u16::from_le_bytes([buffer[4], buffer[5]]),
Expand Down

0 comments on commit 8c84d90

Please sign in to comment.