Run cargo fmt

This commit is contained in:
Sosthène Guédon
2024-12-16 16:14:00 +01:00
committed by sosthene-nitrokey
parent d1e95661d9
commit 37f4da4f19
11 changed files with 164 additions and 83 deletions
+5 -2
View File
@@ -1,5 +1,5 @@
use core::convert::TryInto;
use crate::{Decodable, ErrorKind, Length, Result, TagLike};
use core::convert::TryInto;
/// BER-TLV decoder.
#[derive(Debug)]
@@ -36,7 +36,10 @@ impl<'a> Decoder<'a> {
}
/// Decode a TaggedValue with tag checked to be as expected, returning the value
pub fn decode_tagged_value<T: Decodable<'a> + TagLike, V: Decodable<'a>>(&mut self, tag: T) -> Result<V> {
pub fn decode_tagged_value<T: Decodable<'a> + TagLike, V: Decodable<'a>>(
&mut self,
tag: T,
) -> Result<V> {
let tagged: crate::TaggedSlice<T> = self.decode()?;
tagged.tag().assert_eq(tag)?;
Self::new(tagged.as_bytes()).decode()
+10 -3
View File
@@ -1,5 +1,5 @@
use crate::{header::Header, Encodable, ErrorKind, Length, Result, Tag};
use core::convert::{TryFrom, TryInto};
use crate::{Encodable, ErrorKind, header::Header, Length, Result, Tag};
/// BER-TLV encoder.
#[derive(Debug)]
@@ -58,7 +58,11 @@ impl<'a> Encoder<'a> {
}
/// Encode a collection of values which impl the [`Encodable`] trait under a given tag.
pub fn encode_tagged_collection(&mut self, tag: Tag, encodables: &[&dyn Encodable]) -> Result<()> {
pub fn encode_tagged_collection(
&mut self,
tag: Tag,
encodables: &[&dyn Encodable],
) -> Result<()> {
let expected_len = Length::try_from(encodables)?;
Header::new(tag, expected_len).and_then(|header| header.encode(self))?;
@@ -163,7 +167,10 @@ mod tests {
let tv = TaggedSlice::from(Tag::application(5).constructed(), &[]).unwrap();
let mut buf = [0u8; 4];
assert_eq!(tv.encode_to_slice(&mut buf).unwrap(), &[(0b01 << 6) | (1 << 5) | 5, 0x00]);
assert_eq!(
tv.encode_to_slice(&mut buf).unwrap(),
&[(0b01 << 6) | (1 << 5) | 5, 0x00]
);
}
// use super::Encoder;
+3 -4
View File
@@ -129,7 +129,6 @@ pub enum ErrorKind {
// /// Malformed OID
// Oid,
/// Integer overflow occurred (library bug!)
Overflow,
@@ -184,10 +183,8 @@ pub enum ErrorKind {
// /// Tag of the unexpected value
// tag: Tag,
// },
/// Tag does not fit in 3 bytes
UnsupportedTagSize,
}
impl ErrorKind {
@@ -239,7 +236,9 @@ impl fmt::Display for ErrorKind {
// }
// ErrorKind::Utf8(e) => write!(f, "{}", e),
// ErrorKind::Value { tag } => write!(f, "malformed ASN.1 DER value for {}", tag),
ErrorKind::UnsupportedTagSize => write!(f, "tags occupying more than 3 octets not supported"),
ErrorKind::UnsupportedTagSize => {
write!(f, "tags occupying more than 3 octets not supported")
}
}
}
}
+5 -2
View File
@@ -32,7 +32,10 @@ where
let length = Length::decode(decoder).map_err(|e| {
if e.kind() == ErrorKind::Overlength {
ErrorKind::Length { tag: tag.embedding() }.into()
ErrorKind::Length {
tag: tag.embedding(),
}
.into()
} else {
e
}
@@ -44,7 +47,7 @@ where
impl<T> Encodable for Header<T>
where
T: Encodable
T: Encodable,
{
fn encoded_length(&self) -> Result<Length> {
self.tag.encoded_length()? + self.length.encoded_length()?
-1
View File
@@ -172,7 +172,6 @@ impl Encodable for Length {
}
}
impl fmt::Display for Length {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
+1 -2
View File
@@ -52,13 +52,12 @@ pub use simpletag::SimpleTag;
pub use slice::Slice;
pub use tag::{Class, Tag, TagLike};
pub use tagged::{TaggedSlice, TaggedValue};
pub use traits::{Container, Decodable, Encodable, Tagged};
#[cfg(feature = "heapless")]
pub use traits::EncodableHeapless;
pub use traits::{Container, Decodable, Encodable, Tagged};
// #[derive(Clone, Copy, Debug, Decodable, Encodable, Eq, PartialEq)]
// struct T2<'a> {
// #[tlv(simple = "0x55", slice)]
// a: &'a [u8],
// }
+10 -5
View File
@@ -1,5 +1,7 @@
use crate::{
Decodable, Decoder, Encodable, Encoder, Error, ErrorKind, Length, Result, Tag, TagLike,
};
use core::convert::TryFrom;
use crate::{Decodable, Decoder, Encodable, Encoder, Error, ErrorKind, Length, Result, Tag, TagLike};
/// These are tags like in SIMPLE-TLV.
///
@@ -24,7 +26,11 @@ impl TryFrom<u8> for SimpleTag {
impl TagLike for SimpleTag {
fn embedding(self) -> Tag {
use crate::Class::*;
Tag { class: Universal, constructed: false, number: self.0 as u16 }
Tag {
class: Universal,
constructed: false,
number: self.0 as u16,
}
}
}
@@ -44,18 +50,17 @@ impl Encodable for SimpleTag {
}
}
#[cfg(test)]
mod tests {
use core::convert::TryFrom;
use crate::{Encodable, SimpleTag, TaggedSlice};
use core::convert::TryFrom;
#[test]
fn simple_tag() {
let mut buf = [0u8; 384];
let tag = SimpleTag::try_from(37).unwrap();
let slice = &[1u8,2,3];
let slice = &[1u8, 2, 3];
let short = TaggedSlice::from(tag, slice).unwrap();
assert_eq!(
+1 -2
View File
@@ -1,5 +1,5 @@
use core::convert::TryFrom;
use crate::{Length, Result};
use core::convert::TryFrom;
/// Slice of at most `Length::max()` bytes.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
@@ -42,4 +42,3 @@ impl AsRef<[u8]> for Slice<'_> {
self.as_bytes()
}
}
+55 -18
View File
@@ -1,5 +1,10 @@
use core::{convert::{TryFrom, TryInto}, fmt};
use crate::{Decodable, Decoder, Encodable, Encoder, Error, ErrorKind, Length, Result, TaggedValue};
use crate::{
Decodable, Decoder, Encodable, Encoder, Error, ErrorKind, Length, Result, TaggedValue,
};
use core::{
convert::{TryFrom, TryInto},
fmt,
};
const CLASS_OFFSET: usize = 6;
const CONSTRUCTED_OFFSET: usize = 5;
@@ -42,7 +47,6 @@ pub struct Tag {
pub number: u16,
}
impl Tag {
pub const BOOLEAN: Self = Self::universal(0x1);
pub const INTEGER: Self = Self::universal(0x1);
@@ -58,27 +62,55 @@ impl Tag {
pub const SET: Self = Self::universal(0x11).constructed();
pub fn from(class: Class, constructed: bool, number: u16) -> Self {
Self { class, constructed, number }
Self {
class,
constructed,
number,
}
}
pub const fn universal(number: u16) -> Self {
Self { class: Class::Universal, constructed: false, number }
Self {
class: Class::Universal,
constructed: false,
number,
}
}
pub const fn application(number: u16) -> Self {
Self { class: Class::Application, constructed: false, number }
Self {
class: Class::Application,
constructed: false,
number,
}
}
pub const fn context(number: u16) -> Self {
Self { class: Class::Context, constructed: false, number }
Self {
class: Class::Context,
constructed: false,
number,
}
}
pub const fn private(number: u16) -> Self {
Self { class: Class::Private, constructed: false, number }
Self {
class: Class::Private,
constructed: false,
number,
}
}
pub const fn constructed(self) -> Self {
let Self { class, constructed: _, number } = self;
Self { class, constructed: true, number }
let Self {
class,
constructed: _,
number,
} = self;
Self {
class,
constructed: true,
number,
}
}
}
@@ -144,7 +176,11 @@ impl fmt::Debug for Tag {
let mut buf = [0u8; 3];
let mut encoder = Encoder::new(&mut buf);
encoder.encode(self).unwrap();
write!(f, "Tag(class = {:?}, constructed = {}, number = {})", self.class, self.constructed, self.number)
write!(
f,
"Tag(class = {:?}, constructed = {}, number = {})",
self.class, self.constructed, self.number
)
}
}
@@ -159,8 +195,8 @@ impl Encodable for Tag {
}
fn encode(&self, encoder: &mut Encoder<'_>) -> Result<()> {
let first_byte = ((self.class as u8) << CLASS_OFFSET) | ((self.constructed as u8) << CONSTRUCTED_OFFSET);
let first_byte =
((self.class as u8) << CLASS_OFFSET) | ((self.constructed as u8) << CONSTRUCTED_OFFSET);
match self.number {
0..=0x1E => encoder.byte(first_byte | (self.number as u8)),
@@ -190,9 +226,7 @@ impl Decodable<'_> for Tag {
let first_byte_masked = first_byte & ((1 << 5) - 1);
let number = match first_byte_masked {
number @ 0..=0x1E => {
number as u16
}
number @ 0..=0x1E => number as u16,
_ => {
let second_byte = decoder.byte()?;
if second_byte & NOT_LAST_TAG_OCTET_FLAG == 0 {
@@ -210,11 +244,14 @@ impl Decodable<'_> for Tag {
}
}
};
Ok(Self { class, constructed, number })
Ok(Self {
class,
constructed,
number,
})
}
}
#[cfg(test)]
mod tests {
use crate::{Decodable, Encodable, Tag};
+12 -11
View File
@@ -1,17 +1,20 @@
// //! Common handling for types backed by byte slices with enforcement of the
// //! format-level length limitation of 65,535 bytes.
use crate::{Decodable, Decoder, Encodable, Encoder, ErrorKind, header::Header, Length, Result, Slice, Tag, TagLike};
use crate::{
header::Header, Decodable, Decoder, Encodable, Encoder, ErrorKind, Length, Result, Slice, Tag,
TagLike,
};
/// BER-TLV data object.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct TaggedValue<V, T=Tag> {
pub struct TaggedValue<V, T = Tag> {
tag: T,
value: V,
}
/// Raw BER-TLV data object `TaggedValue<Slice<'_>>`.
pub type TaggedSlice<'a, T=Tag> = TaggedValue<Slice<'a>, T>;
pub type TaggedSlice<'a, T = Tag> = TaggedValue<Slice<'a>, T>;
impl<V, T> TaggedValue<V, T>
where
@@ -55,9 +58,8 @@ where
impl<'a, T> TaggedSlice<'a, T>
where
T: Copy
T: Copy,
{
/// Create a new tagged slice, checking lengths.
pub fn from(tag: T, slice: &'a [u8]) -> Result<Self> {
Slice::new(slice)
@@ -110,14 +112,16 @@ where
let header = Header::<T>::decode(decoder)?;
let tag = header.tag;
let len = header.length.to_usize();
let value = decoder.bytes(len).map_err(|_| ErrorKind::Length { tag: tag.embedding() })?;
let value = decoder.bytes(len).map_err(|_| ErrorKind::Length {
tag: tag.embedding(),
})?;
Self::from(tag, value)
}
}
impl<'a, T> Encodable for TaggedSlice<'a, T>
where
T: Copy + Encodable
T: Copy + Encodable,
{
fn encoded_length(&self) -> Result<Length> {
self.header()?.encoded_length()? + self.length()
@@ -146,11 +150,10 @@ where
// })
// }
#[cfg(test)]
mod tests {
use core::convert::TryFrom;
use crate::{Encodable, Tag, TaggedSlice};
use core::convert::TryFrom;
#[test]
fn encode() {
@@ -204,7 +207,5 @@ mod tests {
let encoded = long.encode_to_slice(&mut buf).unwrap();
assert_eq!(&encoded[..5], &[0xFF, 0x66, 0x82, 0x01, 0x00]);
assert_eq!(&encoded[5..], slice);
}
}
+62 -33
View File
@@ -2,8 +2,8 @@
#![cfg(feature = "derive")]
use flexiber::{Decodable, Encodable};
use flexiber as ber;
use flexiber::{Decodable, Encodable};
#[derive(Clone, Copy, Debug, Decodable, Encodable, Eq, PartialEq)]
#[tlv(number = "0xAA")]
@@ -29,17 +29,18 @@ struct SApp {
#[test]
fn derived_reconstruct() {
let s = S { x: [1,2], y: [3,4,5], z: [6,7,8,9] };
let s = S {
x: [1, 2],
y: [3, 4, 5],
z: [6, 7, 8, 9],
};
let mut buf = [0u8; 1024];
let encoded = s.encode_to_slice(&mut buf).unwrap();
assert_eq!(encoded,
&[0x1F, 0x81, 0x2A, 17,
0x11, 2, 1, 2,
0x1F, 0x22, 3, 3, 4, 5,
0x1F, 0x33, 4, 6, 7, 8, 9,
],
assert_eq!(
encoded,
&[0x1F, 0x81, 0x2A, 17, 0x11, 2, 1, 2, 0x1F, 0x22, 3, 3, 4, 5, 0x1F, 0x33, 4, 6, 7, 8, 9,],
);
let s2 = S::from_bytes(encoded).unwrap();
@@ -48,17 +49,18 @@ fn derived_reconstruct() {
#[test]
fn derived_reconstruct_application() {
let s = SApp { x: [1,2], y: [3,4,5], z: [6,7,8,9] };
let s = SApp {
x: [1, 2],
y: [3, 4, 5],
z: [6, 7, 8, 9],
};
let mut buf = [0u8; 1024];
let encoded = s.encode_to_slice(&mut buf).unwrap();
assert_eq!(encoded,
&[0x5F, 0x81, 0x2A, 17,
0x11, 2, 1, 2,
0x1F, 0x22, 3, 3, 4, 5,
0x1F, 0x33, 4, 6, 7, 8, 9,
],
assert_eq!(
encoded,
&[0x5F, 0x81, 0x2A, 17, 0x11, 2, 1, 2, 0x1F, 0x22, 3, 3, 4, 5, 0x1F, 0x33, 4, 6, 7, 8, 9,],
);
let s2 = SApp::from_bytes(encoded).unwrap();
@@ -77,7 +79,7 @@ fn pretty_big() {
let mut x = [0u8; 1234];
for (i, x) in x.iter_mut().enumerate() {
*x = i as _;
};
}
let t = T { x };
@@ -87,11 +89,22 @@ fn pretty_big() {
let mut buf = [0u8; 1500];
let encoded = t.encode_to_slice(&mut buf).unwrap();
assert_eq!(&encoded[..9], [
// 1234 + 5
0x30, 0x82, 0x04, 0xD2 + 5,
// 1234
0x1F, 0x44, 0x82, 0x04, 0xD2]);
assert_eq!(
&encoded[..9],
[
// 1234 + 5
0x30,
0x82,
0x04,
0xD2 + 5,
// 1234
0x1F,
0x44,
0x82,
0x04,
0xD2
]
);
assert_eq!(&encoded[9..], x);
let t2 = T::from_bytes(encoded).unwrap();
@@ -111,18 +124,25 @@ fn derive_untagged() {
let mut x = [0u8; 1234];
for (i, x) in x.iter_mut().enumerate() {
*x = i as _;
};
}
let t = T2 { x, a: [17u8; 5] };
let mut buf = [0u8; 1500];
let encoded = t.encode_to_slice(&mut buf).unwrap();
assert_eq!(&encoded[..5], [
// 1234
223, 0x44, 0x82, 0x04, 0xD2]);
assert_eq!(
&encoded[..5],
[
// 1234
223, 0x44, 0x82, 0x04, 0xD2
]
);
assert_eq!(&encoded[5..(encoded.len() - 7)], x);
assert_eq!(&encoded[(encoded.len() - 7)..], [0x55, 5, 17, 17, 17, 17, 17]);
assert_eq!(
&encoded[(encoded.len() - 7)..],
[0x55, 5, 17, 17, 17, 17, 17]
);
let t2 = T2::from_bytes(encoded).unwrap();
assert_eq!(t, t2);
@@ -164,9 +184,17 @@ impl Decodable<'_> for PinUsagePolicy {
global_pin: has_global_pin,
on_card_biometric_comparison: capabilities & (1 << 4) != 0,
has_virtual_contact_interface,
pairing_code_required_for_vci: if has_virtual_contact_interface { Some(capabilities & (1 << 2) != 0) } else { None },
pairing_code_required_for_vci: if has_virtual_contact_interface {
Some(capabilities & (1 << 2) != 0)
} else {
None
},
cardholder_prefers_global_pin: if has_global_pin { Some(raw[1] == 0x20) } else { None },
cardholder_prefers_global_pin: if has_global_pin {
Some(raw[1] == 0x20)
} else {
None
},
})
}
}
@@ -211,7 +239,7 @@ impl Encodable for PinUsagePolicy {
}
#[derive(Decodable, Encodable)]
#[tlv(application, constructed, number = "0x1E")] // = 0x7E
#[tlv(application, constructed, number = "0x1E")] // = 0x7E
pub struct DiscoveryObject {
#[tlv(slice, application, number = "0xF")]
piv_card_application_aid: [u8; 11],
@@ -219,13 +247,11 @@ pub struct DiscoveryObject {
pin_usage_policy: PinUsagePolicy,
}
impl Default for DiscoveryObject {
fn default() -> Self {
Self {
piv_card_application_aid: hex_literal::hex!("A000000308 00001000 0100"),
pin_usage_policy: Default::default(),//[0x40, 0x00],
pin_usage_policy: Default::default(), //[0x40, 0x00],
}
}
}
@@ -235,5 +261,8 @@ fn discovery() {
let disco = DiscoveryObject::default();
let mut buf = [0u8; 64];
let encoded = disco.encode_to_slice(&mut buf).unwrap();
assert_eq!(encoded, hex_literal::hex!("7e124f0ba0000003080000100001005f2f024000"));
assert_eq!(
encoded,
hex_literal::hex!("7e124f0ba0000003080000100001005f2f024000")
);
}