1#[derive(Debug, Clone, PartialEq, Eq)]
6#[non_exhaustive]
7pub struct Block<'a> {
8 pub headers: Vec<&'a str>,
10 pub label: String,
12 pub bytes: Vec<u8>,
14}
15
16pub fn encode(label: &str, bytes: &[u8]) -> String {
19 let encoded = data_encoding::BASE64.encode(bytes);
20 let mut pem = format!("-----BEGIN {label}-----\n");
21 for chunk in encoded.as_bytes().chunks(64) {
22 pem.push_str(core::str::from_utf8(chunk).unwrap_or_default());
23 pem.push('\n');
24 }
25 pem.push_str(&format!("-----END {label}-----\n"));
26 pem
27}
28
29pub fn decode(text: &str) -> Option<Block<'_>> {
32 let mut headers = Vec::new();
33 let mut lines = text.lines();
34 let label = loop {
35 let line = lines.next()?.trim();
36 if let Some(label) = line
37 .strip_prefix("-----BEGIN ")
38 .and_then(|rest| rest.strip_suffix("-----"))
39 {
40 break label.to_owned();
41 }
42 headers.push(line);
43 };
44 let end = format!("-----END {label}-----");
45 let mut body = String::new();
46 loop {
47 let line = lines.next()?.trim();
48 if line == end {
49 break;
50 }
51 body.push_str(line);
52 }
53 let bytes = data_encoding::BASE64.decode(body.as_bytes()).ok()?;
54 Some(Block {
55 headers,
56 label,
57 bytes,
58 })
59}
60
61#[cfg(test)]
62mod tests {
63 use super::*;
64
65 #[test]
66 fn a_block_round_trips_with_its_headers() {
67 let pem = format!("Method: tls\n{}", encode("CERTIFICATE", &[7; 100]));
68 let block = decode(&pem).expect("a block");
69 assert_eq!(block.headers, ["Method: tls"]);
70 assert_eq!(block.label, "CERTIFICATE");
71 assert_eq!(block.bytes, vec![7; 100]);
72 assert!(pem.lines().all(|line| line.len() <= 64));
73 assert!(decode("-----BEGIN X-----\nAAAA\n").is_none());
74 }
75}