Skip to content

Commit 0c63159

Browse files
authored
der: have PemReader decode to Cow::Owned (#2094)
Adds an associated `CAN_READ_SLICE` boolean flag to the `Reader` trait. When false, `Cow` decodes the owned type rather than the borrow one. This makes it possible to use `Cow` with `PemReader`, where it will automatically decode the owned type.
1 parent c8ff2bd commit 0c63159

File tree

4 files changed

+17
-4
lines changed

4 files changed

+17
-4
lines changed

der/src/decode.rs

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -212,14 +212,20 @@ where
212212
}
213213

214214
#[cfg(feature = "alloc")]
215-
impl<'a, T> DecodeValue<'a> for Cow<'a, T>
215+
impl<'a, T, E> DecodeValue<'a> for Cow<'a, T>
216216
where
217217
T: ToOwned + ?Sized,
218-
&'a T: DecodeValue<'a>,
218+
&'a T: DecodeValue<'a, Error = E>,
219+
T::Owned: for<'b> DecodeValue<'b, Error = E>,
220+
E: From<Error> + 'static,
219221
{
220-
type Error = <&'a T as DecodeValue<'a>>::Error;
222+
type Error = E;
221223

222224
fn decode_value<R: Reader<'a>>(reader: &mut R, header: Header) -> Result<Self, Self::Error> {
223-
Ok(Cow::Borrowed(<&'a T>::decode_value(reader, header)?))
225+
if R::CAN_READ_SLICE {
226+
<&'a T>::decode_value(reader, header).map(Cow::Borrowed)
227+
} else {
228+
T::Owned::decode_value(reader, header).map(Cow::Owned)
229+
}
224230
}
225231
}

der/src/reader.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,9 @@ use crate::length::indefinite::read_eoc;
2020

2121
/// Reader trait which reads DER-encoded input.
2222
pub trait Reader<'r>: Clone {
23+
/// Does this reader support the `read_slice` method? (i.e. can it borrow from his input?)
24+
const CAN_READ_SLICE: bool;
25+
2326
/// Get the [`EncodingRules`] which should be applied when decoding the input.
2427
fn encoding_rules(&self) -> EncodingRules;
2528

der/src/reader/pem.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,8 @@ impl<'i> PemReader<'i> {
4343

4444
#[cfg(feature = "pem")]
4545
impl<'i> Reader<'i> for PemReader<'i> {
46+
const CAN_READ_SLICE: bool = false;
47+
4648
fn encoding_rules(&self) -> EncodingRules {
4749
self.encoding_rules
4850
}

der/src/reader/slice.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,8 @@ impl<'a> SliceReader<'a> {
7171
}
7272

7373
impl<'a> Reader<'a> for SliceReader<'a> {
74+
const CAN_READ_SLICE: bool = true;
75+
7476
fn encoding_rules(&self) -> EncodingRules {
7577
self.encoding_rules
7678
}

0 commit comments

Comments
 (0)