Encoding trait.
| 20 | |
| 21 | /// Encoding trait. |
| 22 | pub trait Encode { |
| 23 | /// Compute the length of this value in bytes when encoded as ASN.1 DER. |
| 24 | fn encoded_len(&self) -> Result<Length>; |
| 25 | |
| 26 | /// Encode this value as ASN.1 DER using the provided [`Writer`]. |
| 27 | fn encode(&self, encoder: &mut dyn Writer) -> Result<()>; |
| 28 | |
| 29 | /// Encode this value to the provided byte slice, returning a sub-slice |
| 30 | /// containing the encoded message. |
| 31 | fn encode_to_slice<'a>(&self, buf: &'a mut [u8]) -> Result<&'a [u8]> { |
| 32 | let mut writer = SliceWriter::new(buf); |
| 33 | self.encode(&mut writer)?; |
| 34 | writer.finish() |
| 35 | } |
| 36 | |
| 37 | /// Encode this message as ASN.1 DER, appending it to the provided |
| 38 | /// byte vector. |
| 39 | #[cfg(feature = "alloc")] |
| 40 | #[cfg_attr(docsrs, doc(cfg(feature = "alloc")))] |
| 41 | fn encode_to_vec(&self, buf: &mut Vec<u8>) -> Result<Length> { |
| 42 | let expected_len = usize::try_from(self.encoded_len()?)?; |
| 43 | buf.reserve(expected_len); |
| 44 | buf.extend(iter::repeat(0).take(expected_len)); |
| 45 | |
| 46 | let mut writer = SliceWriter::new(buf); |
| 47 | self.encode(&mut writer)?; |
| 48 | let actual_len = writer.finish()?.len(); |
| 49 | |
| 50 | if expected_len != actual_len { |
| 51 | return Err(ErrorKind::Incomplete { |
| 52 | expected_len: expected_len.try_into()?, |
| 53 | actual_len: actual_len.try_into()?, |
| 54 | } |
| 55 | .into()); |
| 56 | } |
| 57 | |
| 58 | actual_len.try_into() |
| 59 | } |
| 60 | |
| 61 | /// Serialize this message as a byte vector. |
| 62 | #[cfg(feature = "alloc")] |
| 63 | #[cfg_attr(docsrs, doc(cfg(feature = "alloc")))] |
| 64 | fn to_vec(&self) -> Result<Vec<u8>> { |
| 65 | let mut buf = Vec::new(); |
| 66 | self.encode_to_vec(&mut buf)?; |
| 67 | Ok(buf) |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | impl<T> Encode for T |
| 72 | where |
no outgoing calls
no test coverage detected