hickory_proto/rr/rdata/
openpgpkey.rs1use alloc::vec::Vec;
10use core::fmt;
11
12#[cfg(feature = "serde")]
13use serde::{Deserialize, Serialize};
14
15use crate::{
16 error::ProtoResult,
17 rr::{RData, RecordData, RecordDataDecodable, RecordType},
18 serialize::{
19 binary::{BinDecoder, BinEncodable, BinEncoder, DecodeError, Restrict},
20 txt::ParseError,
21 },
22};
23
24#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
32#[derive(Debug, PartialEq, Eq, Hash, Clone)]
33#[non_exhaustive]
34pub struct OPENPGPKEY {
35 pub public_key: Vec<u8>,
39}
40
41impl OPENPGPKEY {
42 pub fn new(public_key: Vec<u8>) -> Self {
49 Self { public_key }
50 }
51
52 pub(crate) fn from_tokens<'i, I: Iterator<Item = &'i str>>(
65 mut tokens: I,
66 ) -> Result<Self, ParseError> {
67 let encoded_public_key = tokens.next().ok_or(ParseError::Message(
68 "OPENPGPKEY public key field is missing",
69 ))?;
70 let public_key = data_encoding::BASE64.decode(encoded_public_key.as_bytes())?;
71 if tokens.next().is_some() {
72 return Err(ParseError::Message("too many fields for OPENPGPKEY"));
73 }
74 Ok(Self::new(public_key))
75 }
76}
77
78impl BinEncodable for OPENPGPKEY {
79 fn emit(&self, encoder: &mut BinEncoder<'_>) -> ProtoResult<()> {
80 encoder.emit_vec(&self.public_key)
81 }
82}
83
84impl<'r> RecordDataDecodable<'r> for OPENPGPKEY {
85 fn read_data(decoder: &mut BinDecoder<'r>, length: Restrict<u16>) -> Result<Self, DecodeError> {
86 let rdata_length = length.map(usize::from).unverified();
87 let public_key =
88 decoder.read_vec(rdata_length)?.unverified();
89 Ok(Self::new(public_key))
90 }
91}
92
93impl RecordData for OPENPGPKEY {
94 fn try_borrow(data: &RData) -> Option<&Self> {
95 match data {
96 RData::OPENPGPKEY(csync) => Some(csync),
97 _ => None,
98 }
99 }
100
101 fn record_type(&self) -> RecordType {
102 RecordType::OPENPGPKEY
103 }
104
105 fn into_rdata(self) -> RData {
106 RData::OPENPGPKEY(self)
107 }
108}
109
110impl fmt::Display for OPENPGPKEY {
123 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
124 f.write_str(&data_encoding::BASE64.encode(&self.public_key))
125 }
126}
127
128#[cfg(test)]
129mod tests {
130 use super::*;
131
132 #[test]
133 fn test_parsing() {
134 assert!(OPENPGPKEY::from_tokens(core::iter::empty()).is_err());
135 assert!(OPENPGPKEY::from_tokens(vec!["äöüäööüä"].into_iter()).is_err());
136 assert!(OPENPGPKEY::from_tokens(vec!["ZmFpbGVk", "äöüäöüö"].into_iter()).is_err());
137
138 assert!(
139 OPENPGPKEY::from_tokens(vec!["dHJ1c3RfZG5zIGlzIGF3ZXNvbWU="].into_iter())
140 .map(|rd| rd == OPENPGPKEY::new(b"trust_dns is awesome".to_vec()))
141 .unwrap_or(false)
142 );
143 assert!(
144 OPENPGPKEY::from_tokens(vec!["c2VsZi1wcmFpc2Ugc3Rpbmtz"].into_iter())
145 .map(|rd| rd == OPENPGPKEY::new(b"self-praise stinks".to_vec()))
146 .unwrap_or(false)
147 );
148 }
149}