use std::fmt;
use crate::{Error, standard_error_codes};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Command {
pub cla: u8,
pub ins: u8,
pub p1: u8,
pub p2: u8,
pub data: Vec<u8>,
pub le: Option<u16>,
}
impl Command {
pub fn to_bytes(&self) -> Result<Vec<u8>, Error> {
let mut apdu = vec![self.cla, self.ins, self.p1, self.p2];
if !self.data.is_empty() {
let lc = u8::try_from(self.data.len())
.map_err(|_| Error::CommandTooLong(self.data.len()))?;
apdu.push(lc);
apdu.extend_from_slice(&self.data);
}
if let Some(le) = self.le {
apdu.push(match le {
256 => 0,
_ => u8::try_from(le).map_err(|_| Error::CommandTooLong(le.into()))?,
});
}
Ok(apdu)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct StatusWord(pub u16);
impl StatusWord {
pub const SUCCESS: Self = Self(0x9000);
#[must_use]
pub fn is_success(self) -> bool {
self == Self::SUCCESS
}
}
impl fmt::Display for StatusWord {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let code = format!("{:02X} {:02X}", self.0 >> 8, self.0 & 0xFF);
match standard_error_codes::describe(self.0) {
Some(description) => write!(f, "{description} ({code})"),
None => f.write_str(&code),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Response {
pub data: Vec<u8>,
pub status: StatusWord,
}
impl Response {
pub fn parse(raw: &[u8]) -> Result<Self, Error> {
let [data @ .., sw1, sw2] = raw else {
return Err(Error::TruncatedResponse(raw.len()));
};
Ok(Self {
data: data.to_vec(),
status: StatusWord(u16::from_be_bytes([*sw1, *sw2])),
})
}
pub fn into_success(self) -> Result<Vec<u8>, Error> {
if self.status.is_success() {
Ok(self.data)
} else {
Err(Error::Status(self.status))
}
}
}
#[cfg(test)]
mod tests;