use crate::lds::ef::EfParseError;
use crate::lds::tlv::Tlv;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct DgTag(pub u32);
impl DgTag {
pub const fn value(self) -> u32 {
self.0
}
}
impl std::fmt::Display for DgTag {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "0x{:X}", self.0)
}
}
pub fn parse_dg_content(content: &[u8], expected_tag: u32) -> Result<Vec<u8>, EfParseError> {
let tlv =
Tlv::decode(content).map_err(|e| EfParseError::new(format!("Invalid DG wrapper: {e}")))?;
if tlv.tag.value != expected_tag {
return Err(EfParseError::new(format!(
"Invalid tag={:X}, expected tag={:X}",
tlv.tag.value, expected_tag
)));
}
if tlv.encoded_len != content.len() {
return Err(EfParseError::new(format!(
"Trailing bytes after DG TLV: {} extra byte(s)",
content.len() - tlv.encoded_len
)));
}
Ok(tlv.value)
}
#[macro_export]
macro_rules! dg_stub {
($(#[$m:meta])* $name:ident, $fid:expr, $sfi:expr, $tag:expr) => {
$(#[$m])*
#[derive(Debug, Clone)]
pub struct $name {
encoded: Vec<u8>,
}
impl $name {
pub const FID: u16 = $fid;
pub const SFI: u8 = $sfi;
pub const TAG: $crate::lds::df1::dg::DgTag =
$crate::lds::df1::dg::DgTag($tag);
pub fn from_bytes(
data: impl Into<Vec<u8>>,
) -> Result<Self, $crate::lds::ef::EfParseError> {
let encoded = data.into();
let _ = $crate::lds::df1::dg::parse_dg_content(&encoded, $tag)?;
Ok(Self { encoded })
}
}
impl $crate::lds::ef::ElementaryFile for $name {
const FID: u16 = $fid;
const SFI: u8 = $sfi;
fn to_bytes(&self) -> &[u8] {
&self.encoded
}
}
};
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn dg_tag_equality() {
assert_eq!(DgTag(0x61), DgTag(0x61));
assert_ne!(DgTag(0x61), DgTag(0x62));
}
#[test]
fn parse_strips_wrapper() {
let wrapped = Tlv::encode(0x6A, &[0xAA, 0xBB]);
let content = parse_dg_content(&wrapped, 0x6A).unwrap();
assert_eq!(content, vec![0xAA, 0xBB]);
}
#[test]
fn parse_rejects_wrong_tag() {
let wrapped = Tlv::encode(0x61, &[0xAA]);
let err = parse_dg_content(&wrapped, 0x6A).unwrap_err();
assert!(err.0.contains("expected tag=6A"));
}
#[test]
fn parse_rejects_malformed_input() {
let err = parse_dg_content(&[], 0x61).unwrap_err();
assert!(err.0.contains("Invalid DG wrapper"));
}
#[test]
fn parse_rejects_trailing_bytes() {
let mut wrapped = Tlv::encode(0x6A, &[0xAA, 0xBB]);
wrapped.push(0xFF); let err = parse_dg_content(&wrapped, 0x6A).unwrap_err();
assert!(err.0.contains("Trailing bytes"));
}
}