Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions x509-cert/src/serial_number.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
//! X.509 serial number

use core::fmt::Display;

use der::{
asn1::Uint, DecodeValue, EncodeValue, ErrorKind, FixedTag, Header, Length, Reader, Result, Tag,
ValueOrd, Writer,
Expand Down Expand Up @@ -74,6 +76,21 @@ impl FixedTag for SerialNumber {
const TAG: Tag = <Uint as FixedTag>::TAG;
}

impl Display for SerialNumber {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
let mut iter = self.as_bytes().iter().peekable();

while let Some(byte) = iter.next() {
match iter.peek() {
Some(_) => write!(f, "{:02X}:", byte)?,
None => write!(f, "{:02X}", byte)?,
}
}

Ok(())
}
}

// Implement by hand because the derive would create invalid values.
// Use the constructor to create a valid value.
#[cfg(feature = "arbitrary")]
Expand All @@ -88,3 +105,17 @@ impl<'a> arbitrary::Arbitrary<'a> for SerialNumber {
arbitrary::size_hint::and(u32::size_hint(depth), (0, None))
}
}

#[cfg(test)]
mod tests {
use alloc::string::ToString;

use super::*;

#[test]
fn serial_number_display() {
let sn = SerialNumber::new(&[0xAA, 0xBB, 0xCC, 0x01, 0x10, 0x00, 0x11]).unwrap();

assert_eq!(sn.to_string(), "AA:BB:CC:01:10:00:11")
}
}