Add packet helper functions to avoid unwrapping

This commit is contained in:
Sosthène Guédon
2023-06-19 08:45:53 +02:00
committed by sosthene-nitrokey
parent 930982e25c
commit edb14da9b3
2 changed files with 22 additions and 11 deletions
+5 -9
View File
@@ -6,7 +6,7 @@ use crate::{
constants::*,
types::packet::{
Chain, ChainedPacket as _, Command as PacketCommand, DataBlock, Error as PacketError,
ExtPacket, PacketWithData as _, RawPacket, XfrBlock,
ExtPacket, PacketWithData as _, RawPacket, RawPacketExt as _, XfrBlock,
},
};
@@ -385,8 +385,7 @@ where
pub fn send_wait_extension(&mut self) -> bool {
if self.state == State::Processing {
// Need to send a wait extension request.
let mut packet = RawPacket::new();
packet.resize_default(CCID_HEADER_LEN).ok();
let mut packet = RawPacket::zeroed_until(CCID_HEADER_LEN);
packet[0] = 0x80;
packet[6] = self.seq;
@@ -494,16 +493,14 @@ where
}
fn send_slot_status_ok(&mut self) {
let mut packet = RawPacket::new();
packet.resize_default(CCID_HEADER_LEN).ok();
let mut packet = RawPacket::zeroed_until(CCID_HEADER_LEN);
packet[0] = 0x81;
packet[6] = self.seq;
self.send_packet_assuming_possible(packet);
}
fn send_slot_status_error(&mut self, error: Error) {
let mut packet = RawPacket::new();
packet.resize_default(CCID_HEADER_LEN).ok();
let mut packet = RawPacket::zeroed_until(CCID_HEADER_LEN);
packet[0] = 0x6c;
packet[6] = self.seq;
packet[7] = 1 << 6;
@@ -512,8 +509,7 @@ where
}
fn send_parameters(&mut self) {
let mut packet = RawPacket::new();
packet.resize_default(17).ok();
let mut packet = RawPacket::zeroed_until(17);
packet[0] = 0x82;
packet[1] = 7;
packet[6] = self.seq;
+17 -2
View File
@@ -7,12 +7,28 @@ pub type ExtPacket = heapless::Vec<u8, MAX_MSG_LENGTH>;
pub trait RawPacketExt {
fn data_len(&self) -> usize;
fn zeroed() -> Self;
fn zeroed_until(len: usize) -> Self;
}
impl RawPacketExt for RawPacket {
fn data_len(&self) -> usize {
u32::from_le_bytes(self[1..5].try_into().unwrap()) as usize
}
fn zeroed() -> Self {
let mut res = Self::new();
let cap = res.capacity();
res.resize_default(cap).unwrap();
res
}
fn zeroed_until(len: usize) -> Self {
let mut res = Self::new();
let cap = res.capacity();
res.resize_default(len.min(cap)).unwrap();
res
}
}
pub enum Error {
@@ -109,9 +125,8 @@ impl core::fmt::Debug for DataBlock<'_> {
impl From<DataBlock<'_>> for RawPacket {
fn from(block: DataBlock<'_>) -> RawPacket {
let mut packet = RawPacket::new();
let len = block.data.len();
packet.resize_default(CCID_HEADER_LEN + len).ok();
let mut packet = RawPacket::zeroed_until(CCID_HEADER_LEN + len);
packet[0] = 0x80;
packet[1..][..4].copy_from_slice(
&u32::try_from(len)